From 12a281a28eab41cde9a25b34f547c2ee3c46dc4e Mon Sep 17 00:00:00 2001 From: oojacoboo Date: Wed, 18 Dec 2024 13:24:29 +0000 Subject: [PATCH] =?UTF-8?q?Deploying=20to=20gh-pages=20from=20@=20thecodin?= =?UTF-8?q?gmachine/graphqlite@436e69e3b6c5cb2db181ac1d56ace66fc9876fe6=20?= =?UTF-8?q?=F0=9F=9A=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 404.html | 4 ++-- assets/js/{01fe3043.06c86712.js => 01fe3043.2692f6f5.js} | 2 +- assets/js/{029c6d75.599d329c.js => 029c6d75.3dc46451.js} | 2 +- assets/js/{02c5a8b1.1846c306.js => 02c5a8b1.700b0e1a.js} | 2 +- assets/js/{0343976d.77166e71.js => 0343976d.a935053c.js} | 2 +- assets/js/{0370fbfb.4a24ebcb.js => 0370fbfb.1daf1c02.js} | 2 +- assets/js/{03abab96.c0211075.js => 03abab96.a07ccaca.js} | 2 +- assets/js/{03c886f6.e5c176a5.js => 03c886f6.579f399b.js} | 2 +- assets/js/{04610919.db99bd1a.js => 04610919.75bea3c5.js} | 2 +- assets/js/{05e8cfc0.a282a486.js => 05e8cfc0.b3c9b9a7.js} | 2 +- assets/js/{05fed6b1.dc35b3f9.js => 05fed6b1.d73b7c21.js} | 2 +- assets/js/{06c02cc7.52e92924.js => 06c02cc7.9e169703.js} | 2 +- assets/js/{07623f9a.c14947dc.js => 07623f9a.4dc114b5.js} | 2 +- assets/js/{07666c14.2332900a.js => 07666c14.632db5d1.js} | 2 +- assets/js/{077a13b8.a2553195.js => 077a13b8.cd744d8f.js} | 2 +- assets/js/{079b0d3e.43598dd6.js => 079b0d3e.8f199a77.js} | 2 +- assets/js/{07c49ebd.a4bb9e2a.js => 07c49ebd.142b8e9f.js} | 2 +- assets/js/{085c135f.62109324.js => 085c135f.41ba6b03.js} | 2 +- assets/js/{08fe23a4.0c7fa6f6.js => 08fe23a4.5847e977.js} | 2 +- assets/js/{0a57d896.ef16c98f.js => 0a57d896.ae7e2a2c.js} | 2 +- assets/js/{0cb7e976.d95c0503.js => 0cb7e976.58b0ec3b.js} | 2 +- assets/js/{0d7bb119.dc71c1b6.js => 0d7bb119.a92797bd.js} | 2 +- assets/js/{0db009bb.a3ed74ef.js => 0db009bb.45448590.js} | 2 +- assets/js/{0db959c8.7a233fd1.js => 0db959c8.87e96419.js} | 2 +- assets/js/{0df2ba32.d45e3652.js => 0df2ba32.40734af9.js} | 2 +- assets/js/{0e5befdb.e4236bca.js => 0e5befdb.a35881e8.js} | 2 +- assets/js/{0ef60658.74119e9a.js => 0ef60658.f01d1130.js} | 2 +- assets/js/{0fd21208.44507640.js => 0fd21208.7331e278.js} | 2 +- assets/js/{102de343.140e06b8.js => 102de343.7ec5ba9d.js} | 2 +- assets/js/{107b7a36.81035d33.js => 107b7a36.702ad825.js} | 2 +- assets/js/{107d11ee.6d0f76ea.js => 107d11ee.7808e72a.js} | 2 +- assets/js/{12d3ef9e.8e115802.js => 12d3ef9e.a1c01304.js} | 2 +- assets/js/{136c1ee9.c64b8dee.js => 136c1ee9.09b72467.js} | 2 +- assets/js/{13b4aeb1.58680537.js => 13b4aeb1.853bf41f.js} | 2 +- assets/js/{1428bdad.5f092d25.js => 1428bdad.e9676a5b.js} | 2 +- assets/js/{143f7888.4bece173.js => 143f7888.7046ae9e.js} | 2 +- assets/js/{15a79915.03cabaec.js => 15a79915.ba618513.js} | 2 +- assets/js/{15b5a907.a1750297.js => 15b5a907.3862c567.js} | 2 +- assets/js/{16017aa6.9376b16b.js => 16017aa6.eadedf44.js} | 2 +- assets/js/{16565e6a.70e7214b.js => 16565e6a.7840e1d0.js} | 2 +- assets/js/{17518879.a0c1a1bd.js => 17518879.4eba4643.js} | 2 +- assets/js/{17cca601.1d79c6ae.js => 17cca601.2aca0642.js} | 2 +- assets/js/{18100524.82b29572.js => 18100524.0c790315.js} | 2 +- assets/js/{1891fd2b.20ea55e4.js => 1891fd2b.a8e3c91b.js} | 2 +- assets/js/{18d6c9c9.6704a06c.js => 18d6c9c9.e70b6848.js} | 2 +- assets/js/{1aa05129.6d8f74c5.js => 1aa05129.c022cfc4.js} | 2 +- assets/js/{1af245cd.de613831.js => 1af245cd.1a292e94.js} | 2 +- assets/js/{1b1927f4.f6cb8ea8.js => 1b1927f4.d6cee834.js} | 2 +- assets/js/{1ba75d10.53c389e0.js => 1ba75d10.d93ecfdd.js} | 2 +- assets/js/{1ca907c0.c014be77.js => 1ca907c0.0d0f4c41.js} | 2 +- assets/js/{1d20a4b3.7d27119c.js => 1d20a4b3.4bdc2a57.js} | 2 +- assets/js/{1d703573.702ab7f9.js => 1d703573.eba89edd.js} | 2 +- assets/js/{1e2c5f46.45e28f07.js => 1e2c5f46.65b9961d.js} | 2 +- assets/js/{1e6ec01e.de27ac75.js => 1e6ec01e.ac95ff0a.js} | 2 +- assets/js/{1e7fe27e.a69acb67.js => 1e7fe27e.46ea8ff8.js} | 2 +- assets/js/{1ea13486.734e5d0e.js => 1ea13486.63f904ea.js} | 2 +- assets/js/{1edb88e5.94425734.js => 1edb88e5.0bec25f2.js} | 2 +- assets/js/{1f5af0f2.48924c16.js => 1f5af0f2.7701c5a6.js} | 2 +- assets/js/{1f5e9707.a495c84c.js => 1f5e9707.687e3b9b.js} | 2 +- assets/js/{2014e4e3.9d786417.js => 2014e4e3.18ddacc7.js} | 2 +- assets/js/{20540af3.5d51fb83.js => 20540af3.0917bd96.js} | 2 +- assets/js/{21637dff.64b940b8.js => 21637dff.7d2208c1.js} | 2 +- assets/js/{21a7a3b0.116eca1b.js => 21a7a3b0.1330d704.js} | 2 +- assets/js/{21cde469.cb440bf0.js => 21cde469.ef6b9adb.js} | 2 +- assets/js/{22e1e32f.c82c5b5b.js => 22e1e32f.08dbebdc.js} | 2 +- assets/js/{232afa3a.5a5417be.js => 232afa3a.11ff0b56.js} | 2 +- assets/js/{2355609d.52420cde.js => 2355609d.7d53c238.js} | 2 +- assets/js/{23794275.7217b836.js => 23794275.b58c4864.js} | 2 +- assets/js/{23a8ac29.22cce971.js => 23a8ac29.a124ce1b.js} | 2 +- assets/js/{23f642f2.ea8060e2.js => 23f642f2.1564dfe4.js} | 2 +- assets/js/{242d99d9.3f57a286.js => 242d99d9.76f7b35a.js} | 2 +- assets/js/{24ac61c7.b7e599f7.js => 24ac61c7.7b8c1194.js} | 2 +- assets/js/{24aca886.920d2cd9.js => 24aca886.5ba7e1af.js} | 2 +- assets/js/{25d4129e.6df76c9d.js => 25d4129e.68e7b119.js} | 2 +- assets/js/{263ebc7a.67b2a230.js => 263ebc7a.12eb452f.js} | 2 +- assets/js/{26662da3.0e9e02ad.js => 26662da3.df295bf1.js} | 2 +- assets/js/{26a27afb.82b76686.js => 26a27afb.2468a3db.js} | 2 +- assets/js/{27258a7d.c0f5f2d7.js => 27258a7d.04470269.js} | 2 +- assets/js/{27b414e3.42dc98ea.js => 27b414e3.69a4785b.js} | 2 +- assets/js/{2830ce57.e1138f0b.js => 2830ce57.b230beae.js} | 2 +- assets/js/{28c12eaf.a6253d51.js => 28c12eaf.97fc0087.js} | 2 +- assets/js/{2917b31e.ba066590.js => 2917b31e.50d9064f.js} | 2 +- assets/js/{29a6c1ba.2f241f7d.js => 29a6c1ba.c9e9fd52.js} | 2 +- assets/js/{29cf2ad6.0007f100.js => 29cf2ad6.e5258851.js} | 2 +- assets/js/{2b26025e.ffb0bc4a.js => 2b26025e.b932bba2.js} | 2 +- assets/js/{2bbfc5d5.6351af1c.js => 2bbfc5d5.fe37f321.js} | 2 +- assets/js/{2d02c83c.a539b294.js => 2d02c83c.1450cf33.js} | 2 +- assets/js/{2d4548df.dd5df81f.js => 2d4548df.7b197969.js} | 2 +- assets/js/{2e25c87f.1ae4714b.js => 2e25c87f.4ba0ae27.js} | 2 +- assets/js/{2e301473.4a75d253.js => 2e301473.a02a214d.js} | 2 +- assets/js/{2ef99682.c87f773f.js => 2ef99682.63771824.js} | 2 +- assets/js/{2f36012a.47f01b7f.js => 2f36012a.9ea7bba6.js} | 2 +- assets/js/{2f46a9d9.fbab3a9d.js => 2f46a9d9.195005ee.js} | 2 +- assets/js/{2fc68ddc.8512b0e9.js => 2fc68ddc.2591b067.js} | 2 +- assets/js/{30940d42.2f77f2a1.js => 30940d42.f7fab1ba.js} | 2 +- assets/js/{31b4e903.bffa68d0.js => 31b4e903.7e63c51e.js} | 2 +- assets/js/{323a980a.0fa1a14b.js => 323a980a.c8a6a4d4.js} | 2 +- assets/js/{32e2b5e3.e118ef3e.js => 32e2b5e3.89351c93.js} | 2 +- assets/js/{332827b4.252983b3.js => 332827b4.8809e5b5.js} | 2 +- assets/js/{346bcb92.7616f868.js => 346bcb92.6c319671.js} | 2 +- assets/js/{354a9b78.e5046e45.js => 354a9b78.e630317e.js} | 2 +- assets/js/{366cfce3.76971fab.js => 366cfce3.e6f66bfb.js} | 2 +- assets/js/{36b1b0cc.0cb2f4db.js => 36b1b0cc.60fff3a5.js} | 2 +- assets/js/{36ddade1.eea21b14.js => 36ddade1.f83468ca.js} | 2 +- assets/js/{379bfe51.dc9f16bf.js => 379bfe51.b4685fa8.js} | 2 +- assets/js/{380575ae.fa09855a.js => 380575ae.5662be3c.js} | 2 +- assets/js/{38317547.3402cbae.js => 38317547.9620f8ef.js} | 2 +- assets/js/{38cf1c7a.8794de2a.js => 38cf1c7a.7604d7f6.js} | 2 +- assets/js/{394f3211.eee0aecd.js => 394f3211.4e1435c5.js} | 2 +- assets/js/{3a3e6a89.82f09992.js => 3a3e6a89.777b0fc3.js} | 2 +- assets/js/{3b486936.9dcce287.js => 3b486936.b8ecca35.js} | 2 +- assets/js/{3b58261a.8918d844.js => 3b58261a.66c89998.js} | 2 +- assets/js/{3c86ad25.fffa6c7c.js => 3c86ad25.272dcc24.js} | 2 +- assets/js/{3d0eb74d.ea970a87.js => 3d0eb74d.caf36d3c.js} | 2 +- assets/js/{3d2d0a86.e2343eb4.js => 3d2d0a86.aa21ee01.js} | 2 +- assets/js/{3f944aba.c6af0b12.js => 3f944aba.b52fcb1d.js} | 2 +- assets/js/{400ddbbb.ff156576.js => 400ddbbb.1bebe130.js} | 2 +- assets/js/{4194805f.f56ce99b.js => 4194805f.4897f28c.js} | 2 +- assets/js/{4445fe20.841208ca.js => 4445fe20.9022a165.js} | 2 +- assets/js/{471c3e37.63dc4aba.js => 471c3e37.a2aad2f1.js} | 2 +- assets/js/{48fde361.7161dff2.js => 48fde361.156e0f5a.js} | 2 +- assets/js/{4a060504.b56ac654.js => 4a060504.af38cde8.js} | 2 +- assets/js/{4a07aaf0.8c69c63d.js => 4a07aaf0.9d21528d.js} | 2 +- assets/js/{4a2da18c.512b4df8.js => 4a2da18c.28608207.js} | 2 +- assets/js/{4aab8b8c.5edf73c4.js => 4aab8b8c.ff6f0690.js} | 2 +- assets/js/{4bdafdff.edd05d37.js => 4bdafdff.a73df832.js} | 2 +- assets/js/{4c5bf49d.322bc4b8.js => 4c5bf49d.21adcfe4.js} | 2 +- assets/js/{4c7f7507.76a2b02b.js => 4c7f7507.2c7ce80d.js} | 2 +- assets/js/{4d00e03a.99c1a8d5.js => 4d00e03a.e54ebabe.js} | 2 +- assets/js/{4d049718.9120e91e.js => 4d049718.c6fcb28d.js} | 2 +- assets/js/{4d68b066.70c9c17d.js => 4d68b066.60b726ef.js} | 2 +- assets/js/{4dd5816e.f6f4f160.js => 4dd5816e.64ab8a1d.js} | 2 +- assets/js/{4dfeb783.8925d06c.js => 4dfeb783.89bb581b.js} | 2 +- assets/js/{4e1a0951.21082f6b.js => 4e1a0951.99886c87.js} | 2 +- assets/js/{4e73bd72.b7b1e3e0.js => 4e73bd72.9eff4f50.js} | 2 +- assets/js/{4ed8ec4c.edc2fc06.js => 4ed8ec4c.bc014f19.js} | 2 +- assets/js/{4f30448a.a01184e8.js => 4f30448a.f6dce50e.js} | 2 +- assets/js/{4f4b6633.de97890f.js => 4f4b6633.efc72abb.js} | 2 +- assets/js/{4f59166d.c301b60f.js => 4f59166d.b3fa1d46.js} | 2 +- assets/js/{4f6c3156.8d5db1a9.js => 4f6c3156.c0232592.js} | 2 +- assets/js/{50122f86.0352807a.js => 50122f86.7392e77a.js} | 2 +- assets/js/{504e6c2d.50e431dd.js => 504e6c2d.e48c7385.js} | 2 +- assets/js/{509d2004.e51dcb3d.js => 509d2004.a4a94e63.js} | 2 +- assets/js/{51b7da58.5824a63a.js => 51b7da58.71ef8366.js} | 2 +- assets/js/{5285d58e.2b72d61e.js => 5285d58e.6fcf2c6d.js} | 2 +- assets/js/{528fe65e.145effa3.js => 528fe65e.8ac08875.js} | 2 +- assets/js/{54c144e4.3cb139c7.js => 54c144e4.dcbaa6f6.js} | 2 +- assets/js/{54ca8693.ab787787.js => 54ca8693.d58f5d8d.js} | 2 +- assets/js/{55c77f1e.e707d5c7.js => 55c77f1e.e0e09ff5.js} | 2 +- assets/js/{56279b5e.81deafd2.js => 56279b5e.29c4d3ad.js} | 2 +- assets/js/{565a5567.0caaaeb8.js => 565a5567.d3e945b5.js} | 2 +- assets/js/{56af72f6.da5bc172.js => 56af72f6.73430305.js} | 2 +- assets/js/{5792f9ba.d52d4095.js => 5792f9ba.65bfc82c.js} | 2 +- assets/js/{579cc8d4.e2729820.js => 579cc8d4.33781386.js} | 2 +- assets/js/{57f5c28c.ec3d26d8.js => 57f5c28c.26873cdb.js} | 2 +- assets/js/{5881f7ec.0fc3f62b.js => 5881f7ec.1970d743.js} | 2 +- assets/js/{58d52345.1f7e6858.js => 58d52345.0df60a2d.js} | 2 +- assets/js/{58e6b30f.700a4ca5.js => 58e6b30f.1331fed5.js} | 2 +- assets/js/{5945e8b0.993bc61e.js => 5945e8b0.b053de15.js} | 2 +- assets/js/{59b1a96c.e9fc4b1c.js => 59b1a96c.d84d6050.js} | 2 +- assets/js/{5a9b411c.5b8587bb.js => 5a9b411c.e5c6ed99.js} | 2 +- assets/js/{5b80a12a.5dab1277.js => 5b80a12a.472efb90.js} | 2 +- assets/js/{5bc7272e.2bdba581.js => 5bc7272e.6ff8df15.js} | 2 +- assets/js/{5d7590c2.bd4657d8.js => 5d7590c2.d4fc2faa.js} | 2 +- assets/js/{5d95c2e4.6d20fea0.js => 5d95c2e4.13c08a29.js} | 2 +- assets/js/{5dde70bf.4154cee0.js => 5dde70bf.477b054f.js} | 2 +- assets/js/{5e21a9be.6ece5c56.js => 5e21a9be.74ae7e21.js} | 2 +- assets/js/{5e352ef4.a0ec87fc.js => 5e352ef4.0bebc6a8.js} | 2 +- assets/js/{5e457383.7f5ab153.js => 5e457383.d7e58f2f.js} | 2 +- assets/js/{5ec7a7fe.9f1d1734.js => 5ec7a7fe.6f344f93.js} | 2 +- assets/js/{5ececfab.58345f33.js => 5ececfab.3e198c19.js} | 2 +- assets/js/{5fa4a5b6.abbb7da4.js => 5fa4a5b6.f2b014e5.js} | 2 +- assets/js/{5fb37434.63d9cb43.js => 5fb37434.af064a87.js} | 2 +- assets/js/{5ffc8074.2da3d499.js => 5ffc8074.a35bb01d.js} | 2 +- assets/js/{606959d6.c75b1bce.js => 606959d6.cd0e5d4c.js} | 2 +- assets/js/{607daa94.a7a587eb.js => 607daa94.4dc9730b.js} | 2 +- assets/js/{60d99771.3813694a.js => 60d99771.5b04a0fd.js} | 2 +- assets/js/{610e7425.71f37a5e.js => 610e7425.8f1eebec.js} | 2 +- assets/js/{612b773e.6e04135c.js => 612b773e.a8952612.js} | 2 +- assets/js/{61595218.830cce27.js => 61595218.dcfd472d.js} | 2 +- assets/js/{617523b3.d0beb915.js => 617523b3.757b91f1.js} | 2 +- assets/js/{61c7d915.69c85a33.js => 61c7d915.fe654e35.js} | 2 +- assets/js/{623b6c78.2efbceef.js => 623b6c78.49a33252.js} | 2 +- assets/js/{64536e1a.1c63ec79.js => 64536e1a.c293a5d2.js} | 2 +- assets/js/{64947e00.dcd10efb.js => 64947e00.75fbabf5.js} | 2 +- assets/js/{652c74f1.6f8e2dfd.js => 652c74f1.8f6d89ec.js} | 2 +- assets/js/{65b8d1d1.be427580.js => 65b8d1d1.2e0aa238.js} | 2 +- assets/js/{673df5d6.c3b07156.js => 673df5d6.7f16b068.js} | 2 +- assets/js/{68b7d615.460d30f2.js => 68b7d615.06b7671d.js} | 2 +- assets/js/{68e30702.6ad10b96.js => 68e30702.2c897d24.js} | 2 +- assets/js/{69f2ab1f.101a90d5.js => 69f2ab1f.1faf5012.js} | 2 +- assets/js/{6a8c9872.7b918e26.js => 6a8c9872.8c4f08ae.js} | 2 +- assets/js/{6ad31330.6147159c.js => 6ad31330.e5c9ae06.js} | 2 +- assets/js/{6b4e0fb4.972829be.js => 6b4e0fb4.af536444.js} | 2 +- assets/js/{6c124661.6c7f6118.js => 6c124661.4af7f962.js} | 2 +- assets/js/{6c14a231.3e308cd7.js => 6c14a231.cd87becb.js} | 2 +- assets/js/{6c4340be.cb8b8de8.js => 6c4340be.080987fe.js} | 2 +- assets/js/{6c6ce37c.6a0331a4.js => 6c6ce37c.2245fbeb.js} | 2 +- assets/js/{6c8ff36a.e7a8c20e.js => 6c8ff36a.4853c20d.js} | 2 +- assets/js/{6cfcfcfb.b23423d9.js => 6cfcfcfb.0dd10615.js} | 2 +- assets/js/{6d89025c.6b2e999b.js => 6d89025c.8c59f230.js} | 2 +- assets/js/{6efd6ec9.5d3e0f7f.js => 6efd6ec9.45f89857.js} | 2 +- assets/js/{6fe30f11.e39ea11f.js => 6fe30f11.5db9e4f0.js} | 2 +- assets/js/{71a56230.55388635.js => 71a56230.13b5bfe0.js} | 2 +- assets/js/{72be5fd7.c66c8d29.js => 72be5fd7.546b0d97.js} | 2 +- assets/js/{72d0dc3a.fd9375e2.js => 72d0dc3a.f74b51d2.js} | 2 +- assets/js/{73ccb1b9.90069866.js => 73ccb1b9.530685ad.js} | 2 +- assets/js/{741df2ae.a683b422.js => 741df2ae.936ca227.js} | 2 +- assets/js/{74383bd8.9ddbd2d1.js => 74383bd8.fc1132ac.js} | 2 +- assets/js/{7515d7ec.4b2d0413.js => 7515d7ec.32145f60.js} | 2 +- assets/js/{756c6ac7.11f1af27.js => 756c6ac7.453122bd.js} | 2 +- assets/js/{75cc8326.b16c1c96.js => 75cc8326.f04a2c05.js} | 2 +- assets/js/{766e1cc8.572d4fd6.js => 766e1cc8.77a3fb64.js} | 2 +- assets/js/{767c28af.f76bd5cf.js => 767c28af.d9ac76d3.js} | 2 +- assets/js/{77cdcd82.1c973b5a.js => 77cdcd82.c070a849.js} | 2 +- assets/js/{7810a993.5828a06b.js => 7810a993.15789c24.js} | 2 +- assets/js/{78619623.4541130b.js => 78619623.c6c9389a.js} | 2 +- assets/js/{78da31a1.5238c789.js => 78da31a1.7208e28d.js} | 2 +- assets/js/{7ade2db5.8dd4e724.js => 7ade2db5.bbfffb1d.js} | 2 +- assets/js/{7afb60b1.92665f44.js => 7afb60b1.e108e213.js} | 2 +- assets/js/{7b417fb4.3878a6d8.js => 7b417fb4.38721118.js} | 2 +- assets/js/{7b54f5d5.53f40c9c.js => 7b54f5d5.c9905422.js} | 2 +- assets/js/{7bf967bc.38b9cf53.js => 7bf967bc.e0a8dc5d.js} | 2 +- assets/js/{7c27e34c.578cf119.js => 7c27e34c.1528c28d.js} | 2 +- assets/js/{7e507331.661fb3a8.js => 7e507331.7852fba8.js} | 2 +- assets/js/{7e63a40e.41e0e0e1.js => 7e63a40e.a7d5d237.js} | 2 +- assets/js/{7ee46e43.68bd2d96.js => 7ee46e43.29e7eea9.js} | 2 +- assets/js/{7f74c501.fe3b3a48.js => 7f74c501.1de07200.js} | 2 +- assets/js/{820db038.99a98fa7.js => 820db038.ab33b329.js} | 2 +- assets/js/{8223875c.75de77e7.js => 8223875c.697480e4.js} | 2 +- assets/js/{822cd419.cca2946f.js => 822cd419.ca58e052.js} | 2 +- assets/js/{82395e72.31f38c8d.js => 82395e72.49c98b08.js} | 2 +- assets/js/{8299d165.c85f1b45.js => 8299d165.a4ac47c1.js} | 2 +- assets/js/{843ebfb4.b37baa9b.js => 843ebfb4.2328701a.js} | 2 +- assets/js/{85339969.02e8c648.js => 85339969.b14499df.js} | 2 +- assets/js/{859fcda7.5fa26c20.js => 859fcda7.b533069a.js} | 2 +- assets/js/{85c72337.54300e03.js => 85c72337.7ed996b5.js} | 2 +- assets/js/{87089bce.9e057df3.js => 87089bce.a9173e85.js} | 2 +- assets/js/{8913b51a.bd94c17c.js => 8913b51a.e13c7382.js} | 2 +- assets/js/{89cae3a7.1a554faa.js => 89cae3a7.ffe79b51.js} | 2 +- assets/js/{89ed63c8.2ff7c8bc.js => 89ed63c8.3a63ee5a.js} | 2 +- assets/js/{8b6bafea.c7a6cf4f.js => 8b6bafea.cd594754.js} | 2 +- assets/js/{8bf32d27.a65e41a7.js => 8bf32d27.ffdbfcf5.js} | 2 +- assets/js/{8c95fc16.bb8492ea.js => 8c95fc16.d1d61a3f.js} | 2 +- assets/js/{8d81badd.bfee7348.js => 8d81badd.fe9f30d2.js} | 2 +- assets/js/{8e97f284.4dfec083.js => 8e97f284.e10357e1.js} | 2 +- assets/js/{8f7abfe1.0fd15954.js => 8f7abfe1.e7a52f5f.js} | 2 +- assets/js/{8f7fa040.2b316d49.js => 8f7fa040.88306093.js} | 2 +- assets/js/{8f951ce3.6f6d22dc.js => 8f951ce3.5a4dc1f3.js} | 2 +- assets/js/{8f967659.9b309dd8.js => 8f967659.d7936e3d.js} | 2 +- assets/js/{9000b231.83f9d52f.js => 9000b231.13a2c4ab.js} | 2 +- assets/js/{9073923c.ef617e12.js => 9073923c.de36f167.js} | 2 +- assets/js/{90e0b7fd.24725f2e.js => 90e0b7fd.5581a186.js} | 2 +- assets/js/{91e22cb6.8a82af14.js => 91e22cb6.f499f373.js} | 2 +- assets/js/{9206a32f.bf2cd8fc.js => 9206a32f.1c791804.js} | 2 +- assets/js/{9279cea7.1e1e0a39.js => 9279cea7.bfbca50a.js} | 2 +- assets/js/{947f2c39.dc4d6da3.js => 947f2c39.5b80a366.js} | 2 +- assets/js/{94ecc552.4ea01d21.js => 94ecc552.3b2f4d51.js} | 2 +- assets/js/{950394a4.c594d384.js => 950394a4.ad4896b0.js} | 2 +- assets/js/{95073452.e4451793.js => 95073452.bb48107c.js} | 2 +- assets/js/{95576100.d95ae89b.js => 95576100.0f56eb6d.js} | 2 +- assets/js/{9664ee55.1e08f94f.js => 9664ee55.c3f50066.js} | 2 +- assets/js/{96877411.b1d01353.js => 96877411.577742e6.js} | 2 +- assets/js/{96fc29fc.9890d336.js => 96fc29fc.fee6f6db.js} | 2 +- assets/js/{9749ab4a.ae341e96.js => 9749ab4a.4554c7eb.js} | 2 +- assets/js/{976f6afc.f299a405.js => 976f6afc.88a5e9dd.js} | 2 +- assets/js/{9953ecde.5b5ca3da.js => 9953ecde.a070338d.js} | 2 +- assets/js/{999289d8.dac2cd6d.js => 999289d8.73089ca7.js} | 2 +- assets/js/{9bbf4a9a.abe2da8e.js => 9bbf4a9a.f9d0f062.js} | 2 +- assets/js/{9bd507da.8a54c024.js => 9bd507da.346f47b6.js} | 2 +- assets/js/{9d336ee4.a389bf5f.js => 9d336ee4.5353010a.js} | 2 +- assets/js/{9d9f8394.3b18f36b.js => 9d9f8394.722fb0cd.js} | 2 +- assets/js/{9f0ecd2e.5b766b08.js => 9f0ecd2e.f474bd30.js} | 2 +- assets/js/{a0bf4a5f.acd35b74.js => a0bf4a5f.edd3ca79.js} | 2 +- assets/js/{a13f3cdc.739720d4.js => a13f3cdc.bce6936a.js} | 2 +- assets/js/{a16ee953.d02d6cc1.js => a16ee953.29db8d4b.js} | 2 +- assets/js/{a1e3d512.6cf2b1e6.js => a1e3d512.8e8cc309.js} | 2 +- assets/js/{a228ae9b.49370dc4.js => a228ae9b.2a435235.js} | 2 +- assets/js/{a23a5b68.67a39e10.js => a23a5b68.08f8a0a8.js} | 2 +- assets/js/{a264d631.df1707bf.js => a264d631.33587268.js} | 2 +- assets/js/{a27ea030.bb1f8d85.js => a27ea030.dc26afa1.js} | 2 +- assets/js/{a27f6be0.c080cf87.js => a27f6be0.d4e018f5.js} | 2 +- assets/js/{a28aff23.142ca450.js => a28aff23.a3f13e2b.js} | 2 +- assets/js/{a2d3d8d2.827b3b19.js => a2d3d8d2.de206452.js} | 2 +- assets/js/{a30fd8ca.6e705d12.js => a30fd8ca.1c3c185f.js} | 2 +- assets/js/{a320b509.dcda4ae0.js => a320b509.567f3680.js} | 2 +- assets/js/{a3a193a6.9cd17649.js => a3a193a6.b4dee0e0.js} | 2 +- assets/js/{a3c6f073.978dd91e.js => a3c6f073.0ee436f4.js} | 2 +- assets/js/{a55b0daf.785d30b6.js => a55b0daf.6caf9e22.js} | 2 +- assets/js/{a9125b44.2b3ca9e8.js => a9125b44.76fd5a69.js} | 2 +- assets/js/{a91c1a62.0e26beae.js => a91c1a62.7c3e335b.js} | 2 +- assets/js/{a95c9e82.c54a1418.js => a95c9e82.cf629d6f.js} | 2 +- assets/js/{a99e9943.6c07b693.js => a99e9943.c61535a0.js} | 2 +- assets/js/{a9bc4f03.08cf572d.js => a9bc4f03.79e0d8ad.js} | 2 +- assets/js/{aa52484c.81674c15.js => aa52484c.1be28e63.js} | 2 +- assets/js/{aa5b6080.41588e8b.js => aa5b6080.202b05d1.js} | 2 +- assets/js/{aa675676.70580274.js => aa675676.65e35c40.js} | 2 +- assets/js/{aba5bf07.ba5e1374.js => aba5bf07.0d27af80.js} | 2 +- assets/js/{ac8293fa.486d62f6.js => ac8293fa.0add98f9.js} | 2 +- assets/js/{acbaac14.ade72d33.js => acbaac14.459d0ef1.js} | 2 +- assets/js/{ae0a12ed.4d52e402.js => ae0a12ed.dd201707.js} | 2 +- assets/js/{aebf35b6.36a1f25d.js => aebf35b6.76f4300b.js} | 2 +- assets/js/{b06c439f.00df55b4.js => b06c439f.8519d884.js} | 2 +- assets/js/{b0ed7ea5.d01ca2bb.js => b0ed7ea5.2f596615.js} | 2 +- assets/js/{b103c05a.5b731e8a.js => b103c05a.7389b7f1.js} | 2 +- assets/js/{b26a5b84.39f17309.js => b26a5b84.a3068e3f.js} | 2 +- assets/js/{b2d9540a.5ed5cc8c.js => b2d9540a.2e9ca6f7.js} | 2 +- assets/js/{b35d1284.a50b0cce.js => b35d1284.8a45607f.js} | 2 +- assets/js/{b370b50c.36f5b217.js => b370b50c.3d779569.js} | 2 +- assets/js/{b42f5805.2af07bda.js => b42f5805.7f5efebe.js} | 2 +- assets/js/{b4657038.3d7bc7ef.js => b4657038.7c76f1b3.js} | 2 +- assets/js/{b4aea2ce.968ca243.js => b4aea2ce.28ba2067.js} | 2 +- assets/js/{b5d0ac54.3aa583e2.js => b5d0ac54.f18e7f3c.js} | 2 +- assets/js/{b5d32d98.83d31ffc.js => b5d32d98.f05b0f6c.js} | 2 +- assets/js/{b6722b03.4c0cf4e3.js => b6722b03.72cf7e0e.js} | 2 +- assets/js/{b69ed219.14a7f32f.js => b69ed219.fb526318.js} | 2 +- assets/js/{b6a6a31f.3168611a.js => b6a6a31f.c449286c.js} | 2 +- assets/js/{b7442939.ac73da7f.js => b7442939.e9f19ed1.js} | 2 +- assets/js/{b8487569.bdbe52f0.js => b8487569.6f9d53c5.js} | 2 +- assets/js/{b94a1068.3c6fd15a.js => b94a1068.d4092ec3.js} | 2 +- assets/js/{b9d6d6e5.1e186d4a.js => b9d6d6e5.7eec6184.js} | 2 +- assets/js/{b9ea999a.871dcece.js => b9ea999a.bd76e3cd.js} | 2 +- assets/js/{ba7653ad.1fba9352.js => ba7653ad.201e2661.js} | 2 +- assets/js/{bb5ef1b7.9dc60367.js => bb5ef1b7.9bb649c8.js} | 2 +- assets/js/{bb9fe7c3.7c7ff7e3.js => bb9fe7c3.7ddfdfab.js} | 2 +- assets/js/{bcb6471f.09da66bc.js => bcb6471f.da58a603.js} | 2 +- assets/js/{bcc01c83.31bb42be.js => bcc01c83.2bd73636.js} | 2 +- assets/js/{bd2c4a98.25345306.js => bd2c4a98.15bff0c5.js} | 2 +- assets/js/{bda39da3.f5b2adb7.js => bda39da3.a60d43a7.js} | 2 +- assets/js/{bdb33130.adf1fcbf.js => bdb33130.423bf6c8.js} | 2 +- assets/js/{be1f0304.19cc57bd.js => be1f0304.ac099204.js} | 2 +- assets/js/{beccb025.2bce8e1f.js => beccb025.9437bedc.js} | 2 +- assets/js/{bf2a5963.0b8eb41a.js => bf2a5963.64c72590.js} | 2 +- assets/js/{bfe5398f.45ffaac0.js => bfe5398f.26707152.js} | 2 +- assets/js/{c007fb39.c1bd0f68.js => c007fb39.4066ed8c.js} | 2 +- assets/js/{c0fa6485.1913b948.js => c0fa6485.9174cb01.js} | 2 +- assets/js/{c1068675.dbd64ae9.js => c1068675.ee46c7a9.js} | 2 +- assets/js/{c10d4a63.1fc0f2a8.js => c10d4a63.220b95fc.js} | 2 +- assets/js/{c1fe0282.9222037b.js => c1fe0282.80c470cf.js} | 2 +- assets/js/{c275698c.69c19950.js => c275698c.e823393f.js} | 2 +- assets/js/{c329487f.50e7520e.js => c329487f.4fe1c35b.js} | 2 +- assets/js/{c32ff706.5698427e.js => c32ff706.4951bde3.js} | 2 +- assets/js/{c3701568.dbcc1dc8.js => c3701568.cab1ce33.js} | 2 +- assets/js/{c4d37b36.db54eec4.js => c4d37b36.ec117dcc.js} | 2 +- assets/js/{c5fa393d.6e77de51.js => c5fa393d.e1f9c3bd.js} | 2 +- assets/js/{c69dda99.f81fee58.js => c69dda99.c65ae7cf.js} | 2 +- assets/js/{c6df2ddc.421fe189.js => c6df2ddc.78d6c143.js} | 2 +- assets/js/{c7a4caa1.e682f287.js => c7a4caa1.8813fc32.js} | 2 +- assets/js/{c7e7ae18.90632fce.js => c7e7ae18.ee32871a.js} | 2 +- assets/js/{c8bdc4df.d594a844.js => c8bdc4df.3e4aebed.js} | 2 +- assets/js/{c933a311.7f0623e3.js => c933a311.fd1e7675.js} | 2 +- assets/js/{c953ec08.06ab14fb.js => c953ec08.be3c3152.js} | 2 +- assets/js/{ca36df4d.b6a13eda.js => ca36df4d.61047158.js} | 2 +- assets/js/{caa79efa.24eb6a09.js => caa79efa.000a052a.js} | 2 +- assets/js/{cb01db44.be2bef33.js => cb01db44.29ddbf91.js} | 2 +- assets/js/{cc08685c.99b4e529.js => cc08685c.24227d4e.js} | 2 +- assets/js/{cc1c02fe.8c3dea08.js => cc1c02fe.88a58c68.js} | 2 +- assets/js/{cc1f18af.9d430517.js => cc1f18af.cf44e18c.js} | 2 +- assets/js/{cd25a595.a0197dfd.js => cd25a595.98e47423.js} | 2 +- assets/js/{cd30f404.09caf28c.js => cd30f404.91835414.js} | 2 +- assets/js/{cd699560.a312a130.js => cd699560.60280a86.js} | 2 +- assets/js/{cddcd4e6.18a539ee.js => cddcd4e6.37e96033.js} | 2 +- assets/js/{ce95b17c.1a9c939a.js => ce95b17c.086e4223.js} | 2 +- assets/js/{cf877cff.7ca61dac.js => cf877cff.27151cdf.js} | 2 +- assets/js/{d07ad772.d0f77da4.js => d07ad772.e7609360.js} | 2 +- assets/js/{d3540d59.221c7e6d.js => d3540d59.fa61907b.js} | 2 +- assets/js/{d4446569.50b4e40c.js => d4446569.3cbc548f.js} | 2 +- assets/js/{d49884c9.54104957.js => d49884c9.270e6dca.js} | 2 +- assets/js/{d4c8693b.f893e966.js => d4c8693b.5cb693a0.js} | 2 +- assets/js/{d589d3a7.89953d13.js => d589d3a7.0f1cba51.js} | 2 +- assets/js/{d6188fd4.d65a31dd.js => d6188fd4.b2e76004.js} | 2 +- assets/js/{d62b7e4c.8ec984fe.js => d62b7e4c.41f33cbc.js} | 2 +- assets/js/{d6b4b60c.076729ae.js => d6b4b60c.18c79ff2.js} | 2 +- assets/js/{d7067606.e1cf7b88.js => d7067606.25f18bdb.js} | 2 +- assets/js/{d8037f4c.2fee95fb.js => d8037f4c.c3b97d24.js} | 2 +- assets/js/{d8ff000f.410fde9c.js => d8ff000f.23ad97e0.js} | 2 +- assets/js/{d9523c62.557f0440.js => d9523c62.a8413bae.js} | 2 +- assets/js/{db6a6f31.ea705c74.js => db6a6f31.15ffc30c.js} | 2 +- assets/js/{dbf2bcb3.e7a2a4f7.js => dbf2bcb3.c7a36617.js} | 2 +- assets/js/{dc9a99e0.fb28ae35.js => dc9a99e0.c8144eaf.js} | 2 +- assets/js/{e126d786.6b032437.js => e126d786.b4750660.js} | 2 +- assets/js/{e196b408.a78dca45.js => e196b408.c6be2aa7.js} | 2 +- assets/js/{e1b8bb84.db17b7db.js => e1b8bb84.d0fb13f2.js} | 2 +- assets/js/{e29eb381.b515bb0f.js => e29eb381.db46fb20.js} | 2 +- assets/js/{e2e51976.3c3c26bd.js => e2e51976.67c1d44f.js} | 2 +- assets/js/{e347e63a.ae550287.js => e347e63a.0ae573d4.js} | 2 +- assets/js/{e39283a8.3578b356.js => e39283a8.70a0c24c.js} | 2 +- assets/js/{e45c611c.b3a00efb.js => e45c611c.ca35de63.js} | 2 +- assets/js/{e4c5fdc3.2c80a6e5.js => e4c5fdc3.c11dcebd.js} | 2 +- assets/js/{e5d0e3cb.52fa3839.js => e5d0e3cb.89229e6e.js} | 2 +- assets/js/{e5d7b215.ca62b12f.js => e5d7b215.1d93a1b0.js} | 2 +- assets/js/{e617c97b.6f5afd18.js => e617c97b.1accdd02.js} | 2 +- assets/js/{e63ebe23.04f40872.js => e63ebe23.45e84105.js} | 2 +- assets/js/{e6858589.12658908.js => e6858589.72e37720.js} | 2 +- assets/js/{e688cd7e.064a3472.js => e688cd7e.328d42a5.js} | 2 +- assets/js/{e68b092b.f74e87f3.js => e68b092b.47aa1931.js} | 2 +- assets/js/{e7672013.48d425a0.js => e7672013.44846702.js} | 2 +- assets/js/{e7ffb4b4.d8e071f0.js => e7ffb4b4.789e1741.js} | 2 +- assets/js/{e806c7bf.fca6fc61.js => e806c7bf.6fd79788.js} | 2 +- assets/js/{e8a97ac3.86c008fb.js => e8a97ac3.0a231a8d.js} | 2 +- assets/js/{e91daeb9.fbc54514.js => e91daeb9.8e7131fe.js} | 2 +- assets/js/{eaa287f0.70bd8003.js => eaa287f0.534b794e.js} | 2 +- assets/js/{eb333c39.554c4783.js => eb333c39.d433d098.js} | 2 +- assets/js/{eca0cf35.fa28893f.js => eca0cf35.511fc0e7.js} | 2 +- assets/js/{ece9cf29.85adf6e2.js => ece9cf29.e7a221c7.js} | 2 +- assets/js/{ed0c0463.324ec300.js => ed0c0463.6293e55c.js} | 2 +- assets/js/{eec7caa6.882f2590.js => eec7caa6.1619fe9d.js} | 2 +- assets/js/{f07f4757.206f1033.js => f07f4757.56c56ba2.js} | 2 +- assets/js/{f2710c27.7e389950.js => f2710c27.94ebd814.js} | 2 +- assets/js/{f309eabc.17fc6e9e.js => f309eabc.81e87848.js} | 2 +- assets/js/{f48e2589.563b4cd6.js => f48e2589.fe03d88b.js} | 2 +- assets/js/{f4e1d1ba.0c7d42fe.js => f4e1d1ba.8b13eb66.js} | 2 +- assets/js/{f5b0a435.d957599d.js => f5b0a435.e9c309d4.js} | 2 +- assets/js/{f7c03581.64966720.js => f7c03581.ab9ca9fa.js} | 2 +- assets/js/{f9063551.7d8ac123.js => f9063551.630b68d3.js} | 2 +- assets/js/{f90c5a21.2c8a41a6.js => f90c5a21.e280e7eb.js} | 2 +- assets/js/{f94b062c.e1257188.js => f94b062c.1b4b2049.js} | 2 +- assets/js/{f9511b3d.c73b3d9d.js => f9511b3d.12ef6432.js} | 2 +- assets/js/{f9af357c.7cb47364.js => f9af357c.bd39cc06.js} | 2 +- assets/js/{fa1dd05c.6bfc22c0.js => fa1dd05c.72adee05.js} | 2 +- assets/js/{fa41c0e9.5ce1513d.js => fa41c0e9.957dcfcd.js} | 2 +- assets/js/{fe153c07.0f6f610e.js => fe153c07.ca5ec74e.js} | 2 +- .../{runtime~main.dd419208.js => runtime~main.d8dde0e5.js} | 2 +- docs.html | 6 +++--- docs/3.0.html | 6 +++--- docs/3.0/annotations_reference.html | 6 +++--- docs/3.0/argument-resolving.html | 6 +++--- docs/3.0/authentication_authorization.html | 6 +++--- docs/3.0/autowiring.html | 6 +++--- docs/3.0/custom-output-types.html | 6 +++--- docs/3.0/custom-types.html | 6 +++--- docs/3.0/doctrine-annotations-attributes.html | 6 +++--- docs/3.0/error-handling.html | 6 +++--- docs/3.0/extend_input_type.html | 6 +++--- docs/3.0/extend_type.html | 6 +++--- docs/3.0/external_type_declaration.html | 6 +++--- docs/3.0/field-middlewares.html | 6 +++--- docs/3.0/file-uploads.html | 6 +++--- docs/3.0/fine-grained-security.html | 6 +++--- docs/3.0/getting-started.html | 6 +++--- docs/3.0/implementing-security.html | 6 +++--- docs/3.0/inheritance-interfaces.html | 6 +++--- docs/3.0/inheritance.html | 6 +++--- docs/3.0/input-types.html | 6 +++--- docs/3.0/internals.html | 6 +++--- docs/3.0/laravel-package-advanced.html | 6 +++--- docs/3.0/laravel-package.html | 6 +++--- docs/3.0/migrating.html | 6 +++--- docs/3.0/multiple_output_types.html | 6 +++--- docs/3.0/mutations.html | 6 +++--- docs/3.0/other-frameworks.html | 6 +++--- docs/3.0/pagination.html | 6 +++--- docs/3.0/prefetch-method.html | 6 +++--- docs/3.0/queries.html | 6 +++--- docs/3.0/query-plan.html | 6 +++--- docs/3.0/semver.html | 6 +++--- docs/3.0/symfony-bundle-advanced.html | 6 +++--- docs/3.0/symfony-bundle.html | 6 +++--- docs/3.0/troubleshooting.html | 6 +++--- docs/3.0/type_mapping.html | 6 +++--- docs/3.0/universal_service_providers.html | 6 +++--- docs/3.0/validation.html | 6 +++--- docs/4.0.html | 6 +++--- docs/4.0/annotations_reference.html | 6 +++--- docs/4.0/argument-resolving.html | 6 +++--- docs/4.0/authentication_authorization.html | 6 +++--- docs/4.0/autowiring.html | 6 +++--- docs/4.0/changelog.html | 6 +++--- docs/4.0/custom-output-types.html | 6 +++--- docs/4.0/custom-types.html | 6 +++--- docs/4.0/doctrine-annotations-attributes.html | 6 +++--- docs/4.0/error-handling.html | 6 +++--- docs/4.0/extend_input_type.html | 6 +++--- docs/4.0/extend_type.html | 6 +++--- docs/4.0/external_type_declaration.html | 6 +++--- docs/4.0/field-middlewares.html | 6 +++--- docs/4.0/file-uploads.html | 6 +++--- docs/4.0/fine-grained-security.html | 6 +++--- docs/4.0/getting-started.html | 6 +++--- docs/4.0/implementing-security.html | 6 +++--- docs/4.0/inheritance-interfaces.html | 6 +++--- docs/4.0/inheritance.html | 6 +++--- docs/4.0/input-types.html | 6 +++--- docs/4.0/internals.html | 6 +++--- docs/4.0/laravel-package-advanced.html | 6 +++--- docs/4.0/laravel-package.html | 6 +++--- docs/4.0/migrating.html | 6 +++--- docs/4.0/multiple_output_types.html | 6 +++--- docs/4.0/mutations.html | 6 +++--- docs/4.0/other-frameworks.html | 6 +++--- docs/4.0/pagination.html | 6 +++--- docs/4.0/prefetch-method.html | 6 +++--- docs/4.0/queries.html | 6 +++--- docs/4.0/query-plan.html | 6 +++--- docs/4.0/semver.html | 6 +++--- docs/4.0/symfony-bundle-advanced.html | 6 +++--- docs/4.0/symfony-bundle.html | 6 +++--- docs/4.0/troubleshooting.html | 6 +++--- docs/4.0/type_mapping.html | 6 +++--- docs/4.0/universal_service_providers.html | 6 +++--- docs/4.0/validation.html | 6 +++--- docs/4.1.html | 6 +++--- docs/4.1/annotations_reference.html | 6 +++--- docs/4.1/argument-resolving.html | 6 +++--- docs/4.1/authentication_authorization.html | 6 +++--- docs/4.1/autowiring.html | 6 +++--- docs/4.1/changelog.html | 6 +++--- docs/4.1/custom-output-types.html | 6 +++--- docs/4.1/custom-types.html | 6 +++--- docs/4.1/doctrine-annotations-attributes.html | 6 +++--- docs/4.1/error-handling.html | 6 +++--- docs/4.1/extend_input_type.html | 6 +++--- docs/4.1/extend_type.html | 6 +++--- docs/4.1/external_type_declaration.html | 6 +++--- docs/4.1/field-middlewares.html | 6 +++--- docs/4.1/file-uploads.html | 6 +++--- docs/4.1/fine-grained-security.html | 6 +++--- docs/4.1/getting-started.html | 6 +++--- docs/4.1/implementing-security.html | 6 +++--- docs/4.1/inheritance-interfaces.html | 6 +++--- docs/4.1/inheritance.html | 6 +++--- docs/4.1/input-types.html | 6 +++--- docs/4.1/internals.html | 6 +++--- docs/4.1/laravel-package-advanced.html | 6 +++--- docs/4.1/laravel-package.html | 6 +++--- docs/4.1/migrating.html | 6 +++--- docs/4.1/multiple_output_types.html | 6 +++--- docs/4.1/mutations.html | 6 +++--- docs/4.1/other-frameworks.html | 6 +++--- docs/4.1/pagination.html | 6 +++--- docs/4.1/prefetch-method.html | 6 +++--- docs/4.1/queries.html | 6 +++--- docs/4.1/query-plan.html | 6 +++--- docs/4.1/semver.html | 6 +++--- docs/4.1/symfony-bundle-advanced.html | 6 +++--- docs/4.1/symfony-bundle.html | 6 +++--- docs/4.1/troubleshooting.html | 6 +++--- docs/4.1/type_mapping.html | 6 +++--- docs/4.1/universal_service_providers.html | 6 +++--- docs/4.1/validation.html | 6 +++--- docs/4.2.html | 6 +++--- docs/4.2/annotations-reference.html | 6 +++--- docs/4.2/argument-resolving.html | 6 +++--- docs/4.2/authentication-authorization.html | 6 +++--- docs/4.2/autowiring.html | 6 +++--- docs/4.2/changelog.html | 6 +++--- docs/4.2/custom-types.html | 6 +++--- docs/4.2/doctrine-annotations-attributes.html | 6 +++--- docs/4.2/error-handling.html | 6 +++--- docs/4.2/extend-input-type.html | 6 +++--- docs/4.2/extend-type.html | 6 +++--- docs/4.2/external-type-declaration.html | 6 +++--- docs/4.2/field-middlewares.html | 6 +++--- docs/4.2/file-uploads.html | 6 +++--- docs/4.2/fine-grained-security.html | 6 +++--- docs/4.2/getting-started.html | 6 +++--- docs/4.2/implementing-security.html | 6 +++--- docs/4.2/inheritance-interfaces.html | 6 +++--- docs/4.2/input-types.html | 6 +++--- docs/4.2/internals.html | 6 +++--- docs/4.2/laravel-package-advanced.html | 6 +++--- docs/4.2/laravel-package.html | 6 +++--- docs/4.2/migrating.html | 6 +++--- docs/4.2/multiple-output-types.html | 6 +++--- docs/4.2/mutations.html | 6 +++--- docs/4.2/other-frameworks.html | 6 +++--- docs/4.2/pagination.html | 6 +++--- docs/4.2/prefetch-method.html | 6 +++--- docs/4.2/queries.html | 6 +++--- docs/4.2/query-plan.html | 6 +++--- docs/4.2/semver.html | 6 +++--- docs/4.2/symfony-bundle-advanced.html | 6 +++--- docs/4.2/symfony-bundle.html | 6 +++--- docs/4.2/troubleshooting.html | 6 +++--- docs/4.2/type-mapping.html | 6 +++--- docs/4.2/universal-service-providers.html | 6 +++--- docs/4.2/validation.html | 6 +++--- docs/4.3.html | 6 +++--- docs/4.3/annotations-reference.html | 6 +++--- docs/4.3/argument-resolving.html | 6 +++--- docs/4.3/authentication-authorization.html | 6 +++--- docs/4.3/autowiring.html | 6 +++--- docs/4.3/changelog.html | 6 +++--- docs/4.3/custom-types.html | 6 +++--- docs/4.3/doctrine-annotations-attributes.html | 6 +++--- docs/4.3/error-handling.html | 6 +++--- docs/4.3/extend-input-type.html | 6 +++--- docs/4.3/extend-type.html | 6 +++--- docs/4.3/external-type-declaration.html | 6 +++--- docs/4.3/field-middlewares.html | 6 +++--- docs/4.3/file-uploads.html | 6 +++--- docs/4.3/fine-grained-security.html | 6 +++--- docs/4.3/getting-started.html | 6 +++--- docs/4.3/implementing-security.html | 6 +++--- docs/4.3/inheritance-interfaces.html | 6 +++--- docs/4.3/input-types.html | 6 +++--- docs/4.3/internals.html | 6 +++--- docs/4.3/laravel-package-advanced.html | 6 +++--- docs/4.3/laravel-package.html | 6 +++--- docs/4.3/migrating.html | 6 +++--- docs/4.3/multiple-output-types.html | 6 +++--- docs/4.3/mutations.html | 6 +++--- docs/4.3/other-frameworks.html | 6 +++--- docs/4.3/pagination.html | 6 +++--- docs/4.3/prefetch-method.html | 6 +++--- docs/4.3/queries.html | 6 +++--- docs/4.3/query-plan.html | 6 +++--- docs/4.3/semver.html | 6 +++--- docs/4.3/symfony-bundle-advanced.html | 6 +++--- docs/4.3/symfony-bundle.html | 6 +++--- docs/4.3/troubleshooting.html | 6 +++--- docs/4.3/type-mapping.html | 6 +++--- docs/4.3/universal-service-providers.html | 6 +++--- docs/4.3/validation.html | 6 +++--- docs/5.0.html | 6 +++--- docs/5.0/annotations-reference.html | 6 +++--- docs/5.0/argument-resolving.html | 6 +++--- docs/5.0/authentication-authorization.html | 6 +++--- docs/5.0/autowiring.html | 6 +++--- docs/5.0/changelog.html | 6 +++--- docs/5.0/custom-types.html | 6 +++--- docs/5.0/doctrine-annotations-attributes.html | 6 +++--- docs/5.0/error-handling.html | 6 +++--- docs/5.0/extend-input-type.html | 6 +++--- docs/5.0/extend-type.html | 6 +++--- docs/5.0/external-type-declaration.html | 6 +++--- docs/5.0/field-middlewares.html | 6 +++--- docs/5.0/file-uploads.html | 6 +++--- docs/5.0/fine-grained-security.html | 6 +++--- docs/5.0/getting-started.html | 6 +++--- docs/5.0/implementing-security.html | 6 +++--- docs/5.0/inheritance-interfaces.html | 6 +++--- docs/5.0/input-types.html | 6 +++--- docs/5.0/internals.html | 6 +++--- docs/5.0/laravel-package-advanced.html | 6 +++--- docs/5.0/laravel-package.html | 6 +++--- docs/5.0/migrating.html | 6 +++--- docs/5.0/multiple-output-types.html | 6 +++--- docs/5.0/mutations.html | 6 +++--- docs/5.0/other-frameworks.html | 6 +++--- docs/5.0/pagination.html | 6 +++--- docs/5.0/prefetch-method.html | 6 +++--- docs/5.0/queries.html | 6 +++--- docs/5.0/query-plan.html | 6 +++--- docs/5.0/semver.html | 6 +++--- docs/5.0/symfony-bundle-advanced.html | 6 +++--- docs/5.0/symfony-bundle.html | 6 +++--- docs/5.0/troubleshooting.html | 6 +++--- docs/5.0/type-mapping.html | 6 +++--- docs/5.0/universal-service-providers.html | 6 +++--- docs/5.0/validation.html | 6 +++--- docs/6.0.html | 6 +++--- docs/6.0/annotations-reference.html | 6 +++--- docs/6.0/argument-resolving.html | 6 +++--- docs/6.0/authentication-authorization.html | 6 +++--- docs/6.0/autowiring.html | 6 +++--- docs/6.0/changelog.html | 6 +++--- docs/6.0/custom-types.html | 6 +++--- docs/6.0/doctrine-annotations-attributes.html | 6 +++--- docs/6.0/error-handling.html | 6 +++--- docs/6.0/extend-input-type.html | 6 +++--- docs/6.0/extend-type.html | 6 +++--- docs/6.0/external-type-declaration.html | 6 +++--- docs/6.0/field-middlewares.html | 6 +++--- docs/6.0/file-uploads.html | 6 +++--- docs/6.0/fine-grained-security.html | 6 +++--- docs/6.0/getting-started.html | 6 +++--- docs/6.0/implementing-security.html | 6 +++--- docs/6.0/inheritance-interfaces.html | 6 +++--- docs/6.0/input-types.html | 6 +++--- docs/6.0/internals.html | 6 +++--- docs/6.0/laravel-package-advanced.html | 6 +++--- docs/6.0/laravel-package.html | 6 +++--- docs/6.0/migrating.html | 6 +++--- docs/6.0/multiple-output-types.html | 6 +++--- docs/6.0/mutations.html | 6 +++--- docs/6.0/other-frameworks.html | 6 +++--- docs/6.0/pagination.html | 6 +++--- docs/6.0/prefetch-method.html | 6 +++--- docs/6.0/queries.html | 6 +++--- docs/6.0/query-plan.html | 6 +++--- docs/6.0/semver.html | 6 +++--- docs/6.0/symfony-bundle-advanced.html | 6 +++--- docs/6.0/symfony-bundle.html | 6 +++--- docs/6.0/troubleshooting.html | 6 +++--- docs/6.0/type-mapping.html | 6 +++--- docs/6.0/universal-service-providers.html | 6 +++--- docs/6.0/validation.html | 6 +++--- docs/6.1.html | 6 +++--- docs/6.1/annotations-reference.html | 6 +++--- docs/6.1/argument-resolving.html | 6 +++--- docs/6.1/authentication-authorization.html | 6 +++--- docs/6.1/autowiring.html | 6 +++--- docs/6.1/changelog.html | 6 +++--- docs/6.1/custom-types.html | 6 +++--- docs/6.1/doctrine-annotations-attributes.html | 6 +++--- docs/6.1/error-handling.html | 6 +++--- docs/6.1/extend-input-type.html | 6 +++--- docs/6.1/extend-type.html | 6 +++--- docs/6.1/external-type-declaration.html | 6 +++--- docs/6.1/field-middlewares.html | 6 +++--- docs/6.1/file-uploads.html | 6 +++--- docs/6.1/fine-grained-security.html | 6 +++--- docs/6.1/getting-started.html | 6 +++--- docs/6.1/implementing-security.html | 6 +++--- docs/6.1/inheritance-interfaces.html | 6 +++--- docs/6.1/input-types.html | 6 +++--- docs/6.1/internals.html | 6 +++--- docs/6.1/laravel-package-advanced.html | 6 +++--- docs/6.1/laravel-package.html | 6 +++--- docs/6.1/migrating.html | 6 +++--- docs/6.1/multiple-output-types.html | 6 +++--- docs/6.1/mutations.html | 6 +++--- docs/6.1/other-frameworks.html | 6 +++--- docs/6.1/pagination.html | 6 +++--- docs/6.1/prefetch-method.html | 6 +++--- docs/6.1/queries.html | 6 +++--- docs/6.1/query-plan.html | 6 +++--- docs/6.1/semver.html | 6 +++--- docs/6.1/symfony-bundle-advanced.html | 6 +++--- docs/6.1/symfony-bundle.html | 6 +++--- docs/6.1/troubleshooting.html | 6 +++--- docs/6.1/type-mapping.html | 6 +++--- docs/6.1/universal-service-providers.html | 6 +++--- docs/6.1/validation.html | 6 +++--- docs/7.0.0.html | 6 +++--- docs/7.0.0/annotations-reference.html | 6 +++--- docs/7.0.0/argument-resolving.html | 6 +++--- docs/7.0.0/authentication-authorization.html | 6 +++--- docs/7.0.0/automatic-persisted-queries.html | 6 +++--- docs/7.0.0/autowiring.html | 6 +++--- docs/7.0.0/changelog.html | 6 +++--- docs/7.0.0/custom-types.html | 6 +++--- docs/7.0.0/doctrine-annotations-attributes.html | 6 +++--- docs/7.0.0/error-handling.html | 6 +++--- docs/7.0.0/extend-input-type.html | 6 +++--- docs/7.0.0/extend-type.html | 6 +++--- docs/7.0.0/external-type-declaration.html | 6 +++--- docs/7.0.0/field-middlewares.html | 6 +++--- docs/7.0.0/file-uploads.html | 6 +++--- docs/7.0.0/fine-grained-security.html | 6 +++--- docs/7.0.0/getting-started.html | 6 +++--- docs/7.0.0/implementing-security.html | 6 +++--- docs/7.0.0/inheritance-interfaces.html | 6 +++--- docs/7.0.0/input-types.html | 6 +++--- docs/7.0.0/internals.html | 6 +++--- docs/7.0.0/laravel-package-advanced.html | 6 +++--- docs/7.0.0/laravel-package.html | 6 +++--- docs/7.0.0/migrating.html | 6 +++--- docs/7.0.0/multiple-output-types.html | 6 +++--- docs/7.0.0/mutations.html | 6 +++--- docs/7.0.0/operation-complexity.html | 6 +++--- docs/7.0.0/other-frameworks.html | 6 +++--- docs/7.0.0/pagination.html | 6 +++--- docs/7.0.0/prefetch-method.html | 6 +++--- docs/7.0.0/queries.html | 6 +++--- docs/7.0.0/query-plan.html | 6 +++--- docs/7.0.0/semver.html | 6 +++--- docs/7.0.0/subscriptions.html | 6 +++--- docs/7.0.0/symfony-bundle-advanced.html | 6 +++--- docs/7.0.0/symfony-bundle.html | 6 +++--- docs/7.0.0/troubleshooting.html | 6 +++--- docs/7.0.0/type-mapping.html | 6 +++--- docs/7.0.0/universal-service-providers.html | 6 +++--- docs/7.0.0/validation.html | 6 +++--- docs/annotations-reference.html | 6 +++--- docs/argument-resolving.html | 6 +++--- docs/authentication-authorization.html | 6 +++--- docs/automatic-persisted-queries.html | 6 +++--- docs/autowiring.html | 6 +++--- docs/changelog.html | 6 +++--- docs/custom-types.html | 6 +++--- docs/doctrine-annotations-attributes.html | 6 +++--- docs/error-handling.html | 6 +++--- docs/extend-input-type.html | 6 +++--- docs/extend-type.html | 6 +++--- docs/external-type-declaration.html | 6 +++--- docs/field-middlewares.html | 6 +++--- docs/file-uploads.html | 6 +++--- docs/fine-grained-security.html | 6 +++--- docs/getting-started.html | 6 +++--- docs/implementing-security.html | 6 +++--- docs/inheritance-interfaces.html | 6 +++--- docs/input-types.html | 6 +++--- docs/internals.html | 6 +++--- docs/laravel-package-advanced.html | 6 +++--- docs/laravel-package.html | 6 +++--- docs/migrating.html | 6 +++--- docs/multiple-output-types.html | 6 +++--- docs/mutations.html | 6 +++--- docs/next.html | 6 +++--- docs/next/annotations-reference.html | 6 +++--- docs/next/argument-resolving.html | 6 +++--- docs/next/authentication-authorization.html | 6 +++--- docs/next/automatic-persisted-queries.html | 6 +++--- docs/next/autowiring.html | 6 +++--- docs/next/changelog.html | 6 +++--- docs/next/custom-types.html | 6 +++--- docs/next/doctrine-annotations-attributes.html | 6 +++--- docs/next/error-handling.html | 6 +++--- docs/next/extend-input-type.html | 6 +++--- docs/next/extend-type.html | 6 +++--- docs/next/external-type-declaration.html | 6 +++--- docs/next/field-middlewares.html | 6 +++--- docs/next/file-uploads.html | 6 +++--- docs/next/fine-grained-security.html | 6 +++--- docs/next/getting-started.html | 6 +++--- docs/next/implementing-security.html | 6 +++--- docs/next/inheritance-interfaces.html | 6 +++--- docs/next/input-types.html | 6 +++--- docs/next/internals.html | 6 +++--- docs/next/laravel-package-advanced.html | 6 +++--- docs/next/laravel-package.html | 6 +++--- docs/next/migrating.html | 6 +++--- docs/next/multiple-output-types.html | 6 +++--- docs/next/mutations.html | 6 +++--- docs/next/operation-complexity.html | 6 +++--- docs/next/other-frameworks.html | 6 +++--- docs/next/pagination.html | 6 +++--- docs/next/prefetch-method.html | 6 +++--- docs/next/queries.html | 6 +++--- docs/next/query-plan.html | 6 +++--- docs/next/semver.html | 6 +++--- docs/next/subscriptions.html | 6 +++--- docs/next/symfony-bundle-advanced.html | 6 +++--- docs/next/symfony-bundle.html | 6 +++--- docs/next/troubleshooting.html | 6 +++--- docs/next/type-mapping.html | 6 +++--- docs/next/universal-service-providers.html | 6 +++--- docs/next/validation.html | 6 +++--- docs/operation-complexity.html | 6 +++--- docs/other-frameworks.html | 6 +++--- docs/pagination.html | 6 +++--- docs/prefetch-method.html | 6 +++--- docs/queries.html | 6 +++--- docs/query-plan.html | 6 +++--- docs/semver.html | 6 +++--- docs/subscriptions.html | 6 +++--- docs/symfony-bundle-advanced.html | 6 +++--- docs/symfony-bundle.html | 6 +++--- docs/troubleshooting.html | 6 +++--- docs/type-mapping.html | 6 +++--- docs/universal-service-providers.html | 6 +++--- docs/validation.html | 6 +++--- index.html | 4 ++-- search.html | 4 ++-- 846 files changed, 1691 insertions(+), 1691 deletions(-) rename assets/js/{01fe3043.06c86712.js => 01fe3043.2692f6f5.js} (99%) rename assets/js/{029c6d75.599d329c.js => 029c6d75.3dc46451.js} (99%) rename assets/js/{02c5a8b1.1846c306.js => 02c5a8b1.700b0e1a.js} (99%) rename assets/js/{0343976d.77166e71.js => 0343976d.a935053c.js} (98%) rename assets/js/{0370fbfb.4a24ebcb.js => 0370fbfb.1daf1c02.js} (99%) rename assets/js/{03abab96.c0211075.js => 03abab96.a07ccaca.js} (98%) rename assets/js/{03c886f6.e5c176a5.js => 03c886f6.579f399b.js} (99%) rename assets/js/{04610919.db99bd1a.js => 04610919.75bea3c5.js} (98%) rename assets/js/{05e8cfc0.a282a486.js => 05e8cfc0.b3c9b9a7.js} (98%) rename assets/js/{05fed6b1.dc35b3f9.js => 05fed6b1.d73b7c21.js} (99%) rename assets/js/{06c02cc7.52e92924.js => 06c02cc7.9e169703.js} (98%) rename assets/js/{07623f9a.c14947dc.js => 07623f9a.4dc114b5.js} (99%) rename assets/js/{07666c14.2332900a.js => 07666c14.632db5d1.js} (98%) rename assets/js/{077a13b8.a2553195.js => 077a13b8.cd744d8f.js} (99%) rename assets/js/{079b0d3e.43598dd6.js => 079b0d3e.8f199a77.js} (99%) rename assets/js/{07c49ebd.a4bb9e2a.js => 07c49ebd.142b8e9f.js} (99%) rename assets/js/{085c135f.62109324.js => 085c135f.41ba6b03.js} (99%) rename assets/js/{08fe23a4.0c7fa6f6.js => 08fe23a4.5847e977.js} (96%) rename assets/js/{0a57d896.ef16c98f.js => 0a57d896.ae7e2a2c.js} (99%) rename assets/js/{0cb7e976.d95c0503.js => 0cb7e976.58b0ec3b.js} (99%) rename assets/js/{0d7bb119.dc71c1b6.js => 0d7bb119.a92797bd.js} (98%) rename assets/js/{0db009bb.a3ed74ef.js => 0db009bb.45448590.js} (97%) rename assets/js/{0db959c8.7a233fd1.js => 0db959c8.87e96419.js} (99%) rename assets/js/{0df2ba32.d45e3652.js => 0df2ba32.40734af9.js} (98%) rename assets/js/{0e5befdb.e4236bca.js => 0e5befdb.a35881e8.js} (99%) rename assets/js/{0ef60658.74119e9a.js => 0ef60658.f01d1130.js} (99%) rename assets/js/{0fd21208.44507640.js => 0fd21208.7331e278.js} (96%) rename assets/js/{102de343.140e06b8.js => 102de343.7ec5ba9d.js} (99%) rename assets/js/{107b7a36.81035d33.js => 107b7a36.702ad825.js} (98%) rename assets/js/{107d11ee.6d0f76ea.js => 107d11ee.7808e72a.js} (98%) rename assets/js/{12d3ef9e.8e115802.js => 12d3ef9e.a1c01304.js} (99%) rename assets/js/{136c1ee9.c64b8dee.js => 136c1ee9.09b72467.js} (99%) rename assets/js/{13b4aeb1.58680537.js => 13b4aeb1.853bf41f.js} (98%) rename assets/js/{1428bdad.5f092d25.js => 1428bdad.e9676a5b.js} (99%) rename assets/js/{143f7888.4bece173.js => 143f7888.7046ae9e.js} (99%) rename assets/js/{15a79915.03cabaec.js => 15a79915.ba618513.js} (99%) rename assets/js/{15b5a907.a1750297.js => 15b5a907.3862c567.js} (99%) rename assets/js/{16017aa6.9376b16b.js => 16017aa6.eadedf44.js} (99%) rename assets/js/{16565e6a.70e7214b.js => 16565e6a.7840e1d0.js} (99%) rename assets/js/{17518879.a0c1a1bd.js => 17518879.4eba4643.js} (99%) rename assets/js/{17cca601.1d79c6ae.js => 17cca601.2aca0642.js} (99%) rename assets/js/{18100524.82b29572.js => 18100524.0c790315.js} (99%) rename assets/js/{1891fd2b.20ea55e4.js => 1891fd2b.a8e3c91b.js} (99%) rename assets/js/{18d6c9c9.6704a06c.js => 18d6c9c9.e70b6848.js} (99%) rename assets/js/{1aa05129.6d8f74c5.js => 1aa05129.c022cfc4.js} (98%) rename assets/js/{1af245cd.de613831.js => 1af245cd.1a292e94.js} (99%) rename assets/js/{1b1927f4.f6cb8ea8.js => 1b1927f4.d6cee834.js} (98%) rename assets/js/{1ba75d10.53c389e0.js => 1ba75d10.d93ecfdd.js} (99%) rename assets/js/{1ca907c0.c014be77.js => 1ca907c0.0d0f4c41.js} (98%) rename assets/js/{1d20a4b3.7d27119c.js => 1d20a4b3.4bdc2a57.js} (99%) rename assets/js/{1d703573.702ab7f9.js => 1d703573.eba89edd.js} (97%) rename assets/js/{1e2c5f46.45e28f07.js => 1e2c5f46.65b9961d.js} (98%) rename assets/js/{1e6ec01e.de27ac75.js => 1e6ec01e.ac95ff0a.js} (99%) rename assets/js/{1e7fe27e.a69acb67.js => 1e7fe27e.46ea8ff8.js} (99%) rename assets/js/{1ea13486.734e5d0e.js => 1ea13486.63f904ea.js} (98%) rename assets/js/{1edb88e5.94425734.js => 1edb88e5.0bec25f2.js} (99%) rename assets/js/{1f5af0f2.48924c16.js => 1f5af0f2.7701c5a6.js} (98%) rename assets/js/{1f5e9707.a495c84c.js => 1f5e9707.687e3b9b.js} (99%) rename assets/js/{2014e4e3.9d786417.js => 2014e4e3.18ddacc7.js} (98%) rename assets/js/{20540af3.5d51fb83.js => 20540af3.0917bd96.js} (99%) rename assets/js/{21637dff.64b940b8.js => 21637dff.7d2208c1.js} (99%) rename assets/js/{21a7a3b0.116eca1b.js => 21a7a3b0.1330d704.js} (99%) rename assets/js/{21cde469.cb440bf0.js => 21cde469.ef6b9adb.js} (99%) rename assets/js/{22e1e32f.c82c5b5b.js => 22e1e32f.08dbebdc.js} (99%) rename assets/js/{232afa3a.5a5417be.js => 232afa3a.11ff0b56.js} (99%) rename assets/js/{2355609d.52420cde.js => 2355609d.7d53c238.js} (98%) rename assets/js/{23794275.7217b836.js => 23794275.b58c4864.js} (99%) rename assets/js/{23a8ac29.22cce971.js => 23a8ac29.a124ce1b.js} (99%) rename assets/js/{23f642f2.ea8060e2.js => 23f642f2.1564dfe4.js} (99%) rename assets/js/{242d99d9.3f57a286.js => 242d99d9.76f7b35a.js} (97%) rename assets/js/{24ac61c7.b7e599f7.js => 24ac61c7.7b8c1194.js} (98%) rename assets/js/{24aca886.920d2cd9.js => 24aca886.5ba7e1af.js} (99%) rename assets/js/{25d4129e.6df76c9d.js => 25d4129e.68e7b119.js} (99%) rename assets/js/{263ebc7a.67b2a230.js => 263ebc7a.12eb452f.js} (99%) rename assets/js/{26662da3.0e9e02ad.js => 26662da3.df295bf1.js} (99%) rename assets/js/{26a27afb.82b76686.js => 26a27afb.2468a3db.js} (99%) rename assets/js/{27258a7d.c0f5f2d7.js => 27258a7d.04470269.js} (99%) rename assets/js/{27b414e3.42dc98ea.js => 27b414e3.69a4785b.js} (99%) rename assets/js/{2830ce57.e1138f0b.js => 2830ce57.b230beae.js} (99%) rename assets/js/{28c12eaf.a6253d51.js => 28c12eaf.97fc0087.js} (99%) rename assets/js/{2917b31e.ba066590.js => 2917b31e.50d9064f.js} (99%) rename assets/js/{29a6c1ba.2f241f7d.js => 29a6c1ba.c9e9fd52.js} (99%) rename assets/js/{29cf2ad6.0007f100.js => 29cf2ad6.e5258851.js} (99%) rename assets/js/{2b26025e.ffb0bc4a.js => 2b26025e.b932bba2.js} (97%) rename assets/js/{2bbfc5d5.6351af1c.js => 2bbfc5d5.fe37f321.js} (99%) rename assets/js/{2d02c83c.a539b294.js => 2d02c83c.1450cf33.js} (98%) rename assets/js/{2d4548df.dd5df81f.js => 2d4548df.7b197969.js} (99%) rename assets/js/{2e25c87f.1ae4714b.js => 2e25c87f.4ba0ae27.js} (99%) rename assets/js/{2e301473.4a75d253.js => 2e301473.a02a214d.js} (99%) rename assets/js/{2ef99682.c87f773f.js => 2ef99682.63771824.js} (99%) rename assets/js/{2f36012a.47f01b7f.js => 2f36012a.9ea7bba6.js} (98%) rename assets/js/{2f46a9d9.fbab3a9d.js => 2f46a9d9.195005ee.js} (99%) rename assets/js/{2fc68ddc.8512b0e9.js => 2fc68ddc.2591b067.js} (98%) rename assets/js/{30940d42.2f77f2a1.js => 30940d42.f7fab1ba.js} (99%) rename assets/js/{31b4e903.bffa68d0.js => 31b4e903.7e63c51e.js} (97%) rename assets/js/{323a980a.0fa1a14b.js => 323a980a.c8a6a4d4.js} (98%) rename assets/js/{32e2b5e3.e118ef3e.js => 32e2b5e3.89351c93.js} (99%) rename assets/js/{332827b4.252983b3.js => 332827b4.8809e5b5.js} (98%) rename assets/js/{346bcb92.7616f868.js => 346bcb92.6c319671.js} (99%) rename assets/js/{354a9b78.e5046e45.js => 354a9b78.e630317e.js} (98%) rename assets/js/{366cfce3.76971fab.js => 366cfce3.e6f66bfb.js} (99%) rename assets/js/{36b1b0cc.0cb2f4db.js => 36b1b0cc.60fff3a5.js} (99%) rename assets/js/{36ddade1.eea21b14.js => 36ddade1.f83468ca.js} (97%) rename assets/js/{379bfe51.dc9f16bf.js => 379bfe51.b4685fa8.js} (99%) rename assets/js/{380575ae.fa09855a.js => 380575ae.5662be3c.js} (99%) rename assets/js/{38317547.3402cbae.js => 38317547.9620f8ef.js} (98%) rename assets/js/{38cf1c7a.8794de2a.js => 38cf1c7a.7604d7f6.js} (99%) rename assets/js/{394f3211.eee0aecd.js => 394f3211.4e1435c5.js} (99%) rename assets/js/{3a3e6a89.82f09992.js => 3a3e6a89.777b0fc3.js} (99%) rename assets/js/{3b486936.9dcce287.js => 3b486936.b8ecca35.js} (97%) rename assets/js/{3b58261a.8918d844.js => 3b58261a.66c89998.js} (98%) rename assets/js/{3c86ad25.fffa6c7c.js => 3c86ad25.272dcc24.js} (94%) rename assets/js/{3d0eb74d.ea970a87.js => 3d0eb74d.caf36d3c.js} (99%) rename assets/js/{3d2d0a86.e2343eb4.js => 3d2d0a86.aa21ee01.js} (99%) rename assets/js/{3f944aba.c6af0b12.js => 3f944aba.b52fcb1d.js} (98%) rename assets/js/{400ddbbb.ff156576.js => 400ddbbb.1bebe130.js} (99%) rename assets/js/{4194805f.f56ce99b.js => 4194805f.4897f28c.js} (99%) rename assets/js/{4445fe20.841208ca.js => 4445fe20.9022a165.js} (98%) rename assets/js/{471c3e37.63dc4aba.js => 471c3e37.a2aad2f1.js} (99%) rename assets/js/{48fde361.7161dff2.js => 48fde361.156e0f5a.js} (99%) rename assets/js/{4a060504.b56ac654.js => 4a060504.af38cde8.js} (99%) rename assets/js/{4a07aaf0.8c69c63d.js => 4a07aaf0.9d21528d.js} (98%) rename assets/js/{4a2da18c.512b4df8.js => 4a2da18c.28608207.js} (99%) rename assets/js/{4aab8b8c.5edf73c4.js => 4aab8b8c.ff6f0690.js} (99%) rename assets/js/{4bdafdff.edd05d37.js => 4bdafdff.a73df832.js} (99%) rename assets/js/{4c5bf49d.322bc4b8.js => 4c5bf49d.21adcfe4.js} (99%) rename assets/js/{4c7f7507.76a2b02b.js => 4c7f7507.2c7ce80d.js} (99%) rename assets/js/{4d00e03a.99c1a8d5.js => 4d00e03a.e54ebabe.js} (99%) rename assets/js/{4d049718.9120e91e.js => 4d049718.c6fcb28d.js} (99%) rename assets/js/{4d68b066.70c9c17d.js => 4d68b066.60b726ef.js} (98%) rename assets/js/{4dd5816e.f6f4f160.js => 4dd5816e.64ab8a1d.js} (99%) rename assets/js/{4dfeb783.8925d06c.js => 4dfeb783.89bb581b.js} (99%) rename assets/js/{4e1a0951.21082f6b.js => 4e1a0951.99886c87.js} (99%) rename assets/js/{4e73bd72.b7b1e3e0.js => 4e73bd72.9eff4f50.js} (96%) rename assets/js/{4ed8ec4c.edc2fc06.js => 4ed8ec4c.bc014f19.js} (99%) rename assets/js/{4f30448a.a01184e8.js => 4f30448a.f6dce50e.js} (99%) rename assets/js/{4f4b6633.de97890f.js => 4f4b6633.efc72abb.js} (99%) rename assets/js/{4f59166d.c301b60f.js => 4f59166d.b3fa1d46.js} (99%) rename assets/js/{4f6c3156.8d5db1a9.js => 4f6c3156.c0232592.js} (99%) rename assets/js/{50122f86.0352807a.js => 50122f86.7392e77a.js} (98%) rename assets/js/{504e6c2d.50e431dd.js => 504e6c2d.e48c7385.js} (99%) rename assets/js/{509d2004.e51dcb3d.js => 509d2004.a4a94e63.js} (99%) rename assets/js/{51b7da58.5824a63a.js => 51b7da58.71ef8366.js} (99%) rename assets/js/{5285d58e.2b72d61e.js => 5285d58e.6fcf2c6d.js} (99%) rename assets/js/{528fe65e.145effa3.js => 528fe65e.8ac08875.js} (99%) rename assets/js/{54c144e4.3cb139c7.js => 54c144e4.dcbaa6f6.js} (98%) rename assets/js/{54ca8693.ab787787.js => 54ca8693.d58f5d8d.js} (98%) rename assets/js/{55c77f1e.e707d5c7.js => 55c77f1e.e0e09ff5.js} (98%) rename assets/js/{56279b5e.81deafd2.js => 56279b5e.29c4d3ad.js} (99%) rename assets/js/{565a5567.0caaaeb8.js => 565a5567.d3e945b5.js} (98%) rename assets/js/{56af72f6.da5bc172.js => 56af72f6.73430305.js} (99%) rename assets/js/{5792f9ba.d52d4095.js => 5792f9ba.65bfc82c.js} (99%) rename assets/js/{579cc8d4.e2729820.js => 579cc8d4.33781386.js} (98%) rename assets/js/{57f5c28c.ec3d26d8.js => 57f5c28c.26873cdb.js} (99%) rename assets/js/{5881f7ec.0fc3f62b.js => 5881f7ec.1970d743.js} (99%) rename assets/js/{58d52345.1f7e6858.js => 58d52345.0df60a2d.js} (97%) rename assets/js/{58e6b30f.700a4ca5.js => 58e6b30f.1331fed5.js} (99%) rename assets/js/{5945e8b0.993bc61e.js => 5945e8b0.b053de15.js} (99%) rename assets/js/{59b1a96c.e9fc4b1c.js => 59b1a96c.d84d6050.js} (97%) rename assets/js/{5a9b411c.5b8587bb.js => 5a9b411c.e5c6ed99.js} (99%) rename assets/js/{5b80a12a.5dab1277.js => 5b80a12a.472efb90.js} (99%) rename assets/js/{5bc7272e.2bdba581.js => 5bc7272e.6ff8df15.js} (99%) rename assets/js/{5d7590c2.bd4657d8.js => 5d7590c2.d4fc2faa.js} (98%) rename assets/js/{5d95c2e4.6d20fea0.js => 5d95c2e4.13c08a29.js} (97%) rename assets/js/{5dde70bf.4154cee0.js => 5dde70bf.477b054f.js} (99%) rename assets/js/{5e21a9be.6ece5c56.js => 5e21a9be.74ae7e21.js} (99%) rename assets/js/{5e352ef4.a0ec87fc.js => 5e352ef4.0bebc6a8.js} (99%) rename assets/js/{5e457383.7f5ab153.js => 5e457383.d7e58f2f.js} (97%) rename assets/js/{5ec7a7fe.9f1d1734.js => 5ec7a7fe.6f344f93.js} (99%) rename assets/js/{5ececfab.58345f33.js => 5ececfab.3e198c19.js} (99%) rename assets/js/{5fa4a5b6.abbb7da4.js => 5fa4a5b6.f2b014e5.js} (99%) rename assets/js/{5fb37434.63d9cb43.js => 5fb37434.af064a87.js} (98%) rename assets/js/{5ffc8074.2da3d499.js => 5ffc8074.a35bb01d.js} (99%) rename assets/js/{606959d6.c75b1bce.js => 606959d6.cd0e5d4c.js} (99%) rename assets/js/{607daa94.a7a587eb.js => 607daa94.4dc9730b.js} (99%) rename assets/js/{60d99771.3813694a.js => 60d99771.5b04a0fd.js} (98%) rename assets/js/{610e7425.71f37a5e.js => 610e7425.8f1eebec.js} (99%) rename assets/js/{612b773e.6e04135c.js => 612b773e.a8952612.js} (96%) rename assets/js/{61595218.830cce27.js => 61595218.dcfd472d.js} (99%) rename assets/js/{617523b3.d0beb915.js => 617523b3.757b91f1.js} (99%) rename assets/js/{61c7d915.69c85a33.js => 61c7d915.fe654e35.js} (98%) rename assets/js/{623b6c78.2efbceef.js => 623b6c78.49a33252.js} (99%) rename assets/js/{64536e1a.1c63ec79.js => 64536e1a.c293a5d2.js} (99%) rename assets/js/{64947e00.dcd10efb.js => 64947e00.75fbabf5.js} (99%) rename assets/js/{652c74f1.6f8e2dfd.js => 652c74f1.8f6d89ec.js} (99%) rename assets/js/{65b8d1d1.be427580.js => 65b8d1d1.2e0aa238.js} (99%) rename assets/js/{673df5d6.c3b07156.js => 673df5d6.7f16b068.js} (99%) rename assets/js/{68b7d615.460d30f2.js => 68b7d615.06b7671d.js} (99%) rename assets/js/{68e30702.6ad10b96.js => 68e30702.2c897d24.js} (99%) rename assets/js/{69f2ab1f.101a90d5.js => 69f2ab1f.1faf5012.js} (99%) rename assets/js/{6a8c9872.7b918e26.js => 6a8c9872.8c4f08ae.js} (99%) rename assets/js/{6ad31330.6147159c.js => 6ad31330.e5c9ae06.js} (97%) rename assets/js/{6b4e0fb4.972829be.js => 6b4e0fb4.af536444.js} (99%) rename assets/js/{6c124661.6c7f6118.js => 6c124661.4af7f962.js} (98%) rename assets/js/{6c14a231.3e308cd7.js => 6c14a231.cd87becb.js} (99%) rename assets/js/{6c4340be.cb8b8de8.js => 6c4340be.080987fe.js} (99%) rename assets/js/{6c6ce37c.6a0331a4.js => 6c6ce37c.2245fbeb.js} (97%) rename assets/js/{6c8ff36a.e7a8c20e.js => 6c8ff36a.4853c20d.js} (99%) rename assets/js/{6cfcfcfb.b23423d9.js => 6cfcfcfb.0dd10615.js} (99%) rename assets/js/{6d89025c.6b2e999b.js => 6d89025c.8c59f230.js} (99%) rename assets/js/{6efd6ec9.5d3e0f7f.js => 6efd6ec9.45f89857.js} (99%) rename assets/js/{6fe30f11.e39ea11f.js => 6fe30f11.5db9e4f0.js} (99%) rename assets/js/{71a56230.55388635.js => 71a56230.13b5bfe0.js} (97%) rename assets/js/{72be5fd7.c66c8d29.js => 72be5fd7.546b0d97.js} (99%) rename assets/js/{72d0dc3a.fd9375e2.js => 72d0dc3a.f74b51d2.js} (97%) rename assets/js/{73ccb1b9.90069866.js => 73ccb1b9.530685ad.js} (99%) rename assets/js/{741df2ae.a683b422.js => 741df2ae.936ca227.js} (99%) rename assets/js/{74383bd8.9ddbd2d1.js => 74383bd8.fc1132ac.js} (99%) rename assets/js/{7515d7ec.4b2d0413.js => 7515d7ec.32145f60.js} (99%) rename assets/js/{756c6ac7.11f1af27.js => 756c6ac7.453122bd.js} (99%) rename assets/js/{75cc8326.b16c1c96.js => 75cc8326.f04a2c05.js} (99%) rename assets/js/{766e1cc8.572d4fd6.js => 766e1cc8.77a3fb64.js} (99%) rename assets/js/{767c28af.f76bd5cf.js => 767c28af.d9ac76d3.js} (99%) rename assets/js/{77cdcd82.1c973b5a.js => 77cdcd82.c070a849.js} (97%) rename assets/js/{7810a993.5828a06b.js => 7810a993.15789c24.js} (99%) rename assets/js/{78619623.4541130b.js => 78619623.c6c9389a.js} (99%) rename assets/js/{78da31a1.5238c789.js => 78da31a1.7208e28d.js} (99%) rename assets/js/{7ade2db5.8dd4e724.js => 7ade2db5.bbfffb1d.js} (98%) rename assets/js/{7afb60b1.92665f44.js => 7afb60b1.e108e213.js} (99%) rename assets/js/{7b417fb4.3878a6d8.js => 7b417fb4.38721118.js} (98%) rename assets/js/{7b54f5d5.53f40c9c.js => 7b54f5d5.c9905422.js} (99%) rename assets/js/{7bf967bc.38b9cf53.js => 7bf967bc.e0a8dc5d.js} (98%) rename assets/js/{7c27e34c.578cf119.js => 7c27e34c.1528c28d.js} (95%) rename assets/js/{7e507331.661fb3a8.js => 7e507331.7852fba8.js} (98%) rename assets/js/{7e63a40e.41e0e0e1.js => 7e63a40e.a7d5d237.js} (98%) rename assets/js/{7ee46e43.68bd2d96.js => 7ee46e43.29e7eea9.js} (98%) rename assets/js/{7f74c501.fe3b3a48.js => 7f74c501.1de07200.js} (98%) rename assets/js/{820db038.99a98fa7.js => 820db038.ab33b329.js} (99%) rename assets/js/{8223875c.75de77e7.js => 8223875c.697480e4.js} (99%) rename assets/js/{822cd419.cca2946f.js => 822cd419.ca58e052.js} (98%) rename assets/js/{82395e72.31f38c8d.js => 82395e72.49c98b08.js} (99%) rename assets/js/{8299d165.c85f1b45.js => 8299d165.a4ac47c1.js} (99%) rename assets/js/{843ebfb4.b37baa9b.js => 843ebfb4.2328701a.js} (99%) rename assets/js/{85339969.02e8c648.js => 85339969.b14499df.js} (99%) rename assets/js/{859fcda7.5fa26c20.js => 859fcda7.b533069a.js} (97%) rename assets/js/{85c72337.54300e03.js => 85c72337.7ed996b5.js} (99%) rename assets/js/{87089bce.9e057df3.js => 87089bce.a9173e85.js} (99%) rename assets/js/{8913b51a.bd94c17c.js => 8913b51a.e13c7382.js} (98%) rename assets/js/{89cae3a7.1a554faa.js => 89cae3a7.ffe79b51.js} (99%) rename assets/js/{89ed63c8.2ff7c8bc.js => 89ed63c8.3a63ee5a.js} (99%) rename assets/js/{8b6bafea.c7a6cf4f.js => 8b6bafea.cd594754.js} (99%) rename assets/js/{8bf32d27.a65e41a7.js => 8bf32d27.ffdbfcf5.js} (99%) rename assets/js/{8c95fc16.bb8492ea.js => 8c95fc16.d1d61a3f.js} (99%) rename assets/js/{8d81badd.bfee7348.js => 8d81badd.fe9f30d2.js} (99%) rename assets/js/{8e97f284.4dfec083.js => 8e97f284.e10357e1.js} (98%) rename assets/js/{8f7abfe1.0fd15954.js => 8f7abfe1.e7a52f5f.js} (99%) rename assets/js/{8f7fa040.2b316d49.js => 8f7fa040.88306093.js} (99%) rename assets/js/{8f951ce3.6f6d22dc.js => 8f951ce3.5a4dc1f3.js} (99%) rename assets/js/{8f967659.9b309dd8.js => 8f967659.d7936e3d.js} (98%) rename assets/js/{9000b231.83f9d52f.js => 9000b231.13a2c4ab.js} (98%) rename assets/js/{9073923c.ef617e12.js => 9073923c.de36f167.js} (98%) rename assets/js/{90e0b7fd.24725f2e.js => 90e0b7fd.5581a186.js} (99%) rename assets/js/{91e22cb6.8a82af14.js => 91e22cb6.f499f373.js} (99%) rename assets/js/{9206a32f.bf2cd8fc.js => 9206a32f.1c791804.js} (99%) rename assets/js/{9279cea7.1e1e0a39.js => 9279cea7.bfbca50a.js} (99%) rename assets/js/{947f2c39.dc4d6da3.js => 947f2c39.5b80a366.js} (99%) rename assets/js/{94ecc552.4ea01d21.js => 94ecc552.3b2f4d51.js} (99%) rename assets/js/{950394a4.c594d384.js => 950394a4.ad4896b0.js} (99%) rename assets/js/{95073452.e4451793.js => 95073452.bb48107c.js} (98%) rename assets/js/{95576100.d95ae89b.js => 95576100.0f56eb6d.js} (99%) rename assets/js/{9664ee55.1e08f94f.js => 9664ee55.c3f50066.js} (99%) rename assets/js/{96877411.b1d01353.js => 96877411.577742e6.js} (99%) rename assets/js/{96fc29fc.9890d336.js => 96fc29fc.fee6f6db.js} (99%) rename assets/js/{9749ab4a.ae341e96.js => 9749ab4a.4554c7eb.js} (99%) rename assets/js/{976f6afc.f299a405.js => 976f6afc.88a5e9dd.js} (99%) rename assets/js/{9953ecde.5b5ca3da.js => 9953ecde.a070338d.js} (98%) rename assets/js/{999289d8.dac2cd6d.js => 999289d8.73089ca7.js} (99%) rename assets/js/{9bbf4a9a.abe2da8e.js => 9bbf4a9a.f9d0f062.js} (99%) rename assets/js/{9bd507da.8a54c024.js => 9bd507da.346f47b6.js} (98%) rename assets/js/{9d336ee4.a389bf5f.js => 9d336ee4.5353010a.js} (99%) rename assets/js/{9d9f8394.3b18f36b.js => 9d9f8394.722fb0cd.js} (97%) rename assets/js/{9f0ecd2e.5b766b08.js => 9f0ecd2e.f474bd30.js} (99%) rename assets/js/{a0bf4a5f.acd35b74.js => a0bf4a5f.edd3ca79.js} (99%) rename assets/js/{a13f3cdc.739720d4.js => a13f3cdc.bce6936a.js} (99%) rename assets/js/{a16ee953.d02d6cc1.js => a16ee953.29db8d4b.js} (99%) rename assets/js/{a1e3d512.6cf2b1e6.js => a1e3d512.8e8cc309.js} (99%) rename assets/js/{a228ae9b.49370dc4.js => a228ae9b.2a435235.js} (99%) rename assets/js/{a23a5b68.67a39e10.js => a23a5b68.08f8a0a8.js} (99%) rename assets/js/{a264d631.df1707bf.js => a264d631.33587268.js} (99%) rename assets/js/{a27ea030.bb1f8d85.js => a27ea030.dc26afa1.js} (98%) rename assets/js/{a27f6be0.c080cf87.js => a27f6be0.d4e018f5.js} (98%) rename assets/js/{a28aff23.142ca450.js => a28aff23.a3f13e2b.js} (99%) rename assets/js/{a2d3d8d2.827b3b19.js => a2d3d8d2.de206452.js} (99%) rename assets/js/{a30fd8ca.6e705d12.js => a30fd8ca.1c3c185f.js} (99%) rename assets/js/{a320b509.dcda4ae0.js => a320b509.567f3680.js} (99%) rename assets/js/{a3a193a6.9cd17649.js => a3a193a6.b4dee0e0.js} (98%) rename assets/js/{a3c6f073.978dd91e.js => a3c6f073.0ee436f4.js} (98%) rename assets/js/{a55b0daf.785d30b6.js => a55b0daf.6caf9e22.js} (99%) rename assets/js/{a9125b44.2b3ca9e8.js => a9125b44.76fd5a69.js} (99%) rename assets/js/{a91c1a62.0e26beae.js => a91c1a62.7c3e335b.js} (97%) rename assets/js/{a95c9e82.c54a1418.js => a95c9e82.cf629d6f.js} (99%) rename assets/js/{a99e9943.6c07b693.js => a99e9943.c61535a0.js} (98%) rename assets/js/{a9bc4f03.08cf572d.js => a9bc4f03.79e0d8ad.js} (99%) rename assets/js/{aa52484c.81674c15.js => aa52484c.1be28e63.js} (98%) rename assets/js/{aa5b6080.41588e8b.js => aa5b6080.202b05d1.js} (99%) rename assets/js/{aa675676.70580274.js => aa675676.65e35c40.js} (99%) rename assets/js/{aba5bf07.ba5e1374.js => aba5bf07.0d27af80.js} (99%) rename assets/js/{ac8293fa.486d62f6.js => ac8293fa.0add98f9.js} (99%) rename assets/js/{acbaac14.ade72d33.js => acbaac14.459d0ef1.js} (99%) rename assets/js/{ae0a12ed.4d52e402.js => ae0a12ed.dd201707.js} (99%) rename assets/js/{aebf35b6.36a1f25d.js => aebf35b6.76f4300b.js} (99%) rename assets/js/{b06c439f.00df55b4.js => b06c439f.8519d884.js} (99%) rename assets/js/{b0ed7ea5.d01ca2bb.js => b0ed7ea5.2f596615.js} (99%) rename assets/js/{b103c05a.5b731e8a.js => b103c05a.7389b7f1.js} (99%) rename assets/js/{b26a5b84.39f17309.js => b26a5b84.a3068e3f.js} (99%) rename assets/js/{b2d9540a.5ed5cc8c.js => b2d9540a.2e9ca6f7.js} (99%) rename assets/js/{b35d1284.a50b0cce.js => b35d1284.8a45607f.js} (98%) rename assets/js/{b370b50c.36f5b217.js => b370b50c.3d779569.js} (99%) rename assets/js/{b42f5805.2af07bda.js => b42f5805.7f5efebe.js} (99%) rename assets/js/{b4657038.3d7bc7ef.js => b4657038.7c76f1b3.js} (98%) rename assets/js/{b4aea2ce.968ca243.js => b4aea2ce.28ba2067.js} (98%) rename assets/js/{b5d0ac54.3aa583e2.js => b5d0ac54.f18e7f3c.js} (99%) rename assets/js/{b5d32d98.83d31ffc.js => b5d32d98.f05b0f6c.js} (98%) rename assets/js/{b6722b03.4c0cf4e3.js => b6722b03.72cf7e0e.js} (99%) rename assets/js/{b69ed219.14a7f32f.js => b69ed219.fb526318.js} (99%) rename assets/js/{b6a6a31f.3168611a.js => b6a6a31f.c449286c.js} (98%) rename assets/js/{b7442939.ac73da7f.js => b7442939.e9f19ed1.js} (99%) rename assets/js/{b8487569.bdbe52f0.js => b8487569.6f9d53c5.js} (99%) rename assets/js/{b94a1068.3c6fd15a.js => b94a1068.d4092ec3.js} (99%) rename assets/js/{b9d6d6e5.1e186d4a.js => b9d6d6e5.7eec6184.js} (98%) rename assets/js/{b9ea999a.871dcece.js => b9ea999a.bd76e3cd.js} (99%) rename assets/js/{ba7653ad.1fba9352.js => ba7653ad.201e2661.js} (99%) rename assets/js/{bb5ef1b7.9dc60367.js => bb5ef1b7.9bb649c8.js} (99%) rename assets/js/{bb9fe7c3.7c7ff7e3.js => bb9fe7c3.7ddfdfab.js} (99%) rename assets/js/{bcb6471f.09da66bc.js => bcb6471f.da58a603.js} (99%) rename assets/js/{bcc01c83.31bb42be.js => bcc01c83.2bd73636.js} (99%) rename assets/js/{bd2c4a98.25345306.js => bd2c4a98.15bff0c5.js} (99%) rename assets/js/{bda39da3.f5b2adb7.js => bda39da3.a60d43a7.js} (98%) rename assets/js/{bdb33130.adf1fcbf.js => bdb33130.423bf6c8.js} (99%) rename assets/js/{be1f0304.19cc57bd.js => be1f0304.ac099204.js} (99%) rename assets/js/{beccb025.2bce8e1f.js => beccb025.9437bedc.js} (98%) rename assets/js/{bf2a5963.0b8eb41a.js => bf2a5963.64c72590.js} (99%) rename assets/js/{bfe5398f.45ffaac0.js => bfe5398f.26707152.js} (97%) rename assets/js/{c007fb39.c1bd0f68.js => c007fb39.4066ed8c.js} (99%) rename assets/js/{c0fa6485.1913b948.js => c0fa6485.9174cb01.js} (98%) rename assets/js/{c1068675.dbd64ae9.js => c1068675.ee46c7a9.js} (98%) rename assets/js/{c10d4a63.1fc0f2a8.js => c10d4a63.220b95fc.js} (99%) rename assets/js/{c1fe0282.9222037b.js => c1fe0282.80c470cf.js} (99%) rename assets/js/{c275698c.69c19950.js => c275698c.e823393f.js} (99%) rename assets/js/{c329487f.50e7520e.js => c329487f.4fe1c35b.js} (99%) rename assets/js/{c32ff706.5698427e.js => c32ff706.4951bde3.js} (96%) rename assets/js/{c3701568.dbcc1dc8.js => c3701568.cab1ce33.js} (98%) rename assets/js/{c4d37b36.db54eec4.js => c4d37b36.ec117dcc.js} (99%) rename assets/js/{c5fa393d.6e77de51.js => c5fa393d.e1f9c3bd.js} (98%) rename assets/js/{c69dda99.f81fee58.js => c69dda99.c65ae7cf.js} (99%) rename assets/js/{c6df2ddc.421fe189.js => c6df2ddc.78d6c143.js} (99%) rename assets/js/{c7a4caa1.e682f287.js => c7a4caa1.8813fc32.js} (98%) rename assets/js/{c7e7ae18.90632fce.js => c7e7ae18.ee32871a.js} (99%) rename assets/js/{c8bdc4df.d594a844.js => c8bdc4df.3e4aebed.js} (98%) rename assets/js/{c933a311.7f0623e3.js => c933a311.fd1e7675.js} (99%) rename assets/js/{c953ec08.06ab14fb.js => c953ec08.be3c3152.js} (99%) rename assets/js/{ca36df4d.b6a13eda.js => ca36df4d.61047158.js} (99%) rename assets/js/{caa79efa.24eb6a09.js => caa79efa.000a052a.js} (99%) rename assets/js/{cb01db44.be2bef33.js => cb01db44.29ddbf91.js} (99%) rename assets/js/{cc08685c.99b4e529.js => cc08685c.24227d4e.js} (99%) rename assets/js/{cc1c02fe.8c3dea08.js => cc1c02fe.88a58c68.js} (99%) rename assets/js/{cc1f18af.9d430517.js => cc1f18af.cf44e18c.js} (99%) rename assets/js/{cd25a595.a0197dfd.js => cd25a595.98e47423.js} (99%) rename assets/js/{cd30f404.09caf28c.js => cd30f404.91835414.js} (99%) rename assets/js/{cd699560.a312a130.js => cd699560.60280a86.js} (99%) rename assets/js/{cddcd4e6.18a539ee.js => cddcd4e6.37e96033.js} (99%) rename assets/js/{ce95b17c.1a9c939a.js => ce95b17c.086e4223.js} (98%) rename assets/js/{cf877cff.7ca61dac.js => cf877cff.27151cdf.js} (97%) rename assets/js/{d07ad772.d0f77da4.js => d07ad772.e7609360.js} (99%) rename assets/js/{d3540d59.221c7e6d.js => d3540d59.fa61907b.js} (99%) rename assets/js/{d4446569.50b4e40c.js => d4446569.3cbc548f.js} (99%) rename assets/js/{d49884c9.54104957.js => d49884c9.270e6dca.js} (99%) rename assets/js/{d4c8693b.f893e966.js => d4c8693b.5cb693a0.js} (99%) rename assets/js/{d589d3a7.89953d13.js => d589d3a7.0f1cba51.js} (97%) rename assets/js/{d6188fd4.d65a31dd.js => d6188fd4.b2e76004.js} (98%) rename assets/js/{d62b7e4c.8ec984fe.js => d62b7e4c.41f33cbc.js} (99%) rename assets/js/{d6b4b60c.076729ae.js => d6b4b60c.18c79ff2.js} (99%) rename assets/js/{d7067606.e1cf7b88.js => d7067606.25f18bdb.js} (99%) rename assets/js/{d8037f4c.2fee95fb.js => d8037f4c.c3b97d24.js} (97%) rename assets/js/{d8ff000f.410fde9c.js => d8ff000f.23ad97e0.js} (99%) rename assets/js/{d9523c62.557f0440.js => d9523c62.a8413bae.js} (99%) rename assets/js/{db6a6f31.ea705c74.js => db6a6f31.15ffc30c.js} (99%) rename assets/js/{dbf2bcb3.e7a2a4f7.js => dbf2bcb3.c7a36617.js} (99%) rename assets/js/{dc9a99e0.fb28ae35.js => dc9a99e0.c8144eaf.js} (99%) rename assets/js/{e126d786.6b032437.js => e126d786.b4750660.js} (99%) rename assets/js/{e196b408.a78dca45.js => e196b408.c6be2aa7.js} (98%) rename assets/js/{e1b8bb84.db17b7db.js => e1b8bb84.d0fb13f2.js} (99%) rename assets/js/{e29eb381.b515bb0f.js => e29eb381.db46fb20.js} (99%) rename assets/js/{e2e51976.3c3c26bd.js => e2e51976.67c1d44f.js} (99%) rename assets/js/{e347e63a.ae550287.js => e347e63a.0ae573d4.js} (99%) rename assets/js/{e39283a8.3578b356.js => e39283a8.70a0c24c.js} (99%) rename assets/js/{e45c611c.b3a00efb.js => e45c611c.ca35de63.js} (99%) rename assets/js/{e4c5fdc3.2c80a6e5.js => e4c5fdc3.c11dcebd.js} (98%) rename assets/js/{e5d0e3cb.52fa3839.js => e5d0e3cb.89229e6e.js} (99%) rename assets/js/{e5d7b215.ca62b12f.js => e5d7b215.1d93a1b0.js} (98%) rename assets/js/{e617c97b.6f5afd18.js => e617c97b.1accdd02.js} (99%) rename assets/js/{e63ebe23.04f40872.js => e63ebe23.45e84105.js} (99%) rename assets/js/{e6858589.12658908.js => e6858589.72e37720.js} (96%) rename assets/js/{e688cd7e.064a3472.js => e688cd7e.328d42a5.js} (99%) rename assets/js/{e68b092b.f74e87f3.js => e68b092b.47aa1931.js} (99%) rename assets/js/{e7672013.48d425a0.js => e7672013.44846702.js} (98%) rename assets/js/{e7ffb4b4.d8e071f0.js => e7ffb4b4.789e1741.js} (97%) rename assets/js/{e806c7bf.fca6fc61.js => e806c7bf.6fd79788.js} (99%) rename assets/js/{e8a97ac3.86c008fb.js => e8a97ac3.0a231a8d.js} (99%) rename assets/js/{e91daeb9.fbc54514.js => e91daeb9.8e7131fe.js} (99%) rename assets/js/{eaa287f0.70bd8003.js => eaa287f0.534b794e.js} (99%) rename assets/js/{eb333c39.554c4783.js => eb333c39.d433d098.js} (98%) rename assets/js/{eca0cf35.fa28893f.js => eca0cf35.511fc0e7.js} (99%) rename assets/js/{ece9cf29.85adf6e2.js => ece9cf29.e7a221c7.js} (99%) rename assets/js/{ed0c0463.324ec300.js => ed0c0463.6293e55c.js} (99%) rename assets/js/{eec7caa6.882f2590.js => eec7caa6.1619fe9d.js} (99%) rename assets/js/{f07f4757.206f1033.js => f07f4757.56c56ba2.js} (99%) rename assets/js/{f2710c27.7e389950.js => f2710c27.94ebd814.js} (99%) rename assets/js/{f309eabc.17fc6e9e.js => f309eabc.81e87848.js} (99%) rename assets/js/{f48e2589.563b4cd6.js => f48e2589.fe03d88b.js} (97%) rename assets/js/{f4e1d1ba.0c7d42fe.js => f4e1d1ba.8b13eb66.js} (99%) rename assets/js/{f5b0a435.d957599d.js => f5b0a435.e9c309d4.js} (99%) rename assets/js/{f7c03581.64966720.js => f7c03581.ab9ca9fa.js} (99%) rename assets/js/{f9063551.7d8ac123.js => f9063551.630b68d3.js} (99%) rename assets/js/{f90c5a21.2c8a41a6.js => f90c5a21.e280e7eb.js} (98%) rename assets/js/{f94b062c.e1257188.js => f94b062c.1b4b2049.js} (99%) rename assets/js/{f9511b3d.c73b3d9d.js => f9511b3d.12ef6432.js} (99%) rename assets/js/{f9af357c.7cb47364.js => f9af357c.bd39cc06.js} (99%) rename assets/js/{fa1dd05c.6bfc22c0.js => fa1dd05c.72adee05.js} (99%) rename assets/js/{fa41c0e9.5ce1513d.js => fa41c0e9.957dcfcd.js} (99%) rename assets/js/{fe153c07.0f6f610e.js => fe153c07.ca5ec74e.js} (99%) rename assets/js/{runtime~main.dd419208.js => runtime~main.d8dde0e5.js} (61%) diff --git a/404.html b/404.html index 5962e989c..7cf5b292d 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.06c86712.js b/assets/js/01fe3043.2692f6f5.js similarity index 99% rename from assets/js/01fe3043.06c86712.js rename to assets/js/01fe3043.2692f6f5.js index 08137089f..1aec609dc 100644 --- a/assets/js/01fe3043.06c86712.js +++ b/assets/js/01fe3043.2692f6f5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2743],{20587:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function u(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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([[2743],{20587:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function u(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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.599d329c.js b/assets/js/029c6d75.3dc46451.js similarity index 99% rename from assets/js/029c6d75.599d329c.js rename to assets/js/029c6d75.3dc46451.js index c05b88545..5e740fc14 100644 --- a/assets/js/029c6d75.599d329c.js +++ b/assets/js/029c6d75.3dc46451.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6599],{19365:(e,n,t)=>{t.d(n,{A:()=>u});var a=t(96540),l=t(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:n,hidden:t,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),l=t(96540),r=t(20053),u=t(23104),o=t(56347),i=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.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:l}}=e;return{value:n,label:t,attributes:a,default:l}}))}function d(e){const{values:n,children:t}=e;return(0,l.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 m(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,o.W6)(),r=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.aZ)(r),(0,l.useCallback)((e=>{if(!r)return;const n=new URLSearchParams(a.location.search);n.set(r,e),a.replace({...a.location,search:n.toString()})}),[r,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.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(!m({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:r}))),[i,s]=g({queryString:t,groupId:a}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,r]=(0,c.Dv)(t);return[a,(0,l.useCallback)((e=>{t&&r.set(e)}),[t,r])]}({groupId:a}),h=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);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),y(e)}),[s,y,r]),tabValues:r}}var h=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==o&&(p(n),i(a))},m=e=>{let n=null;switch(e.key){case"Enter":d(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 l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:u}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const r=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,l.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function q(e){const n=y(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,n)),l.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(n)},e))}},14829:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=t(58168),l=(t(96540),t(15680)),r=(t(67443),t(11470)),u=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,l.yg)(m,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("div",{class:"alert alert--warning"},(0,l.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.yg)("p",null,"By settings ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.yg)("p",null,"The mutation below will log-in a user:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.yg)("p",null,"In Symfony, user objects implement ",(0,l.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.yg)("p",null,"If you want to get more fields, just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"You can now query this field using an ",(0,l.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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")))))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6599],{19365:(e,n,t)=>{t.d(n,{A:()=>u});var a=t(96540),l=t(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:n,hidden:t,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),l=t(96540),r=t(20053),u=t(23104),o=t(56347),i=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.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:l}}=e;return{value:n,label:t,attributes:a,default:l}}))}function d(e){const{values:n,children:t}=e;return(0,l.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 m(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,o.W6)(),r=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.aZ)(r),(0,l.useCallback)((e=>{if(!r)return;const n=new URLSearchParams(a.location.search);n.set(r,e),a.replace({...a.location,search:n.toString()})}),[r,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.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(!m({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:r}))),[i,s]=g({queryString:t,groupId:a}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,r]=(0,c.Dv)(t);return[a,(0,l.useCallback)((e=>{t&&r.set(e)}),[t,r])]}({groupId:a}),h=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);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),y(e)}),[s,y,r]),tabValues:r}}var h=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==o&&(p(n),i(a))},m=e=>{let n=null;switch(e.key){case"Enter":d(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 l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:u}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const r=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,l.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function q(e){const n=y(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,n)),l.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(n)},e))}},14829:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=t(58168),l=(t(96540),t(15680)),r=(t(67443),t(11470)),u=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,l.yg)(m,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("div",{class:"alert alert--warning"},(0,l.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.yg)("p",null,"By settings ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.yg)("p",null,"The mutation below will log-in a user:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.yg)("p",null,"In Symfony, user objects implement ",(0,l.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.yg)("p",null,"If you want to get more fields, just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"You can now query this field using an ",(0,l.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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")))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/02c5a8b1.1846c306.js b/assets/js/02c5a8b1.700b0e1a.js similarity index 99% rename from assets/js/02c5a8b1.1846c306.js rename to assets/js/02c5a8b1.700b0e1a.js index c6833bba3..fff956002 100644 --- a/assets/js/02c5a8b1.1846c306.js +++ b/assets/js/02c5a8b1.700b0e1a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1289],{80157:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"docs",previous:{title:"Getting Started",permalink:"/docs/6.1/getting-started"},next:{title:"Laravel package",permalink:"/docs/6.1/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 g(e){let{components:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,i.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Now, go to the ",(0,i.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,i.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"docs",previous:{title:"Getting Started",permalink:"/docs/6.1/getting-started"},next:{title:"Laravel package",permalink:"/docs/6.1/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 g(e){let{components:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,i.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Now, go to the ",(0,i.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,i.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>p,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},c={},u=[],l={toc:u},g="wrapper";function p(e){let{components:t,...n}=e;return(0,r.yg)(g,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--info"},"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package"),(0,r.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.0/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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([[3765],{36664:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>p,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},c={},u=[],l={toc:u},g="wrapper";function p(e){let{components:t,...n}=e;return(0,r.yg)(g,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--info"},"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package"),(0,r.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.0/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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/0370fbfb.4a24ebcb.js b/assets/js/0370fbfb.1daf1c02.js similarity index 99% rename from assets/js/0370fbfb.4a24ebcb.js rename to assets/js/0370fbfb.1daf1c02.js index 2c329c5d1..da79207fb 100644 --- a/assets/js/0370fbfb.4a24ebcb.js +++ b/assets/js/0370fbfb.1daf1c02.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9793],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var r=a(96540),t=a(20053);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,t.A)(o.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>$});var r=a(58168),t=a(96540),o=a(20053),i=a(23104),l=a(56347),s=a(57485),c=a(31682),u=a(89466);function p(e){return function(e){return t.Children.map(e,(e=>{if(!e||(0,t.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:a,attributes:r,default:t}}=e;return{value:n,label:a,attributes:r,default:t}}))}function d(e){const{values:n,children:a}=e;return(0,t.useMemo)((()=>{const e=n??p(a);return function(e){const n=(0,c.X)(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,a])}function h(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:a}=e;const r=(0,l.W6)(),o=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(o),(0,t.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 y(e){const{defaultValue:n,queryString:a=!1,groupId:r}=e,o=d(e),[i,l]=(0,t.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,c]=m({queryString:a,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,u.Dv)(a);return[r,(0,t.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:r}),g=(()=>{const e=s??p;return h({value:e,tabValues:o})?e:null})();(0,t.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:i,selectValue:(0,t.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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),d=e=>{const n=e.currentTarget,a=u.indexOf(n),r=c[a].value;r!==l&&(p(n),s(r))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=u.indexOf(e.currentTarget)+1;n=u[a]??u[0];break}case"ArrowLeft":{const a=u.indexOf(e.currentTarget)-1;n=u[a]??u[u.length-1];break}}n?.focus()};return t.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return t.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":l===n})}),a??n)})))}function w(e){let{lazy:n,children:a,selectedValue:r}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,t.cloneElement)(e,{className:"margin-top--md"}):null}return t.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,t.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=y(e);return t.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},t.createElement(b,(0,r.A)({},e,n)),t.createElement(w,(0,r.A)({},e,n)))}function $(e){const n=(0,g.A)();return t.createElement(v,(0,r.A)({key:String(n)},e))}},79111:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>d,frontMatter:()=>o,metadata:()=>l,toc:()=>c});var r=a(58168),t=(a(96540),a(15680));a(67443),a(11470),a(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.1/universal-service-providers"},next:{title:"Queries",permalink:"/docs/6.1/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:n,...a}=e;return(0,t.yg)(p,(0,r.A)({},u,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("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([[9793],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var r=a(96540),t=a(20053);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,t.A)(o.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>$});var r=a(58168),t=a(96540),o=a(20053),i=a(23104),l=a(56347),s=a(57485),c=a(31682),u=a(89466);function p(e){return function(e){return t.Children.map(e,(e=>{if(!e||(0,t.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:a,attributes:r,default:t}}=e;return{value:n,label:a,attributes:r,default:t}}))}function d(e){const{values:n,children:a}=e;return(0,t.useMemo)((()=>{const e=n??p(a);return function(e){const n=(0,c.X)(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,a])}function h(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:a}=e;const r=(0,l.W6)(),o=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(o),(0,t.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 y(e){const{defaultValue:n,queryString:a=!1,groupId:r}=e,o=d(e),[i,l]=(0,t.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,c]=m({queryString:a,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,u.Dv)(a);return[r,(0,t.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:r}),g=(()=>{const e=s??p;return h({value:e,tabValues:o})?e:null})();(0,t.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:i,selectValue:(0,t.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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),d=e=>{const n=e.currentTarget,a=u.indexOf(n),r=c[a].value;r!==l&&(p(n),s(r))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=u.indexOf(e.currentTarget)+1;n=u[a]??u[0];break}case"ArrowLeft":{const a=u.indexOf(e.currentTarget)-1;n=u[a]??u[u.length-1];break}}n?.focus()};return t.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return t.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":l===n})}),a??n)})))}function w(e){let{lazy:n,children:a,selectedValue:r}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,t.cloneElement)(e,{className:"margin-top--md"}):null}return t.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,t.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=y(e);return t.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},t.createElement(b,(0,r.A)({},e,n)),t.createElement(w,(0,r.A)({},e,n)))}function $(e){const n=(0,g.A)();return t.createElement(v,(0,r.A)({key:String(n)},e))}},79111:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>d,frontMatter:()=>o,metadata:()=>l,toc:()=>c});var r=a(58168),t=(a(96540),a(15680));a(67443),a(11470),a(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.1/universal-service-providers"},next:{title:"Queries",permalink:"/docs/6.1/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:n,...a}=e;return(0,t.yg)(p,(0,r.A)({},u,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("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.c0211075.js b/assets/js/03abab96.a07ccaca.js similarity index 98% rename from assets/js/03abab96.c0211075.js rename to assets/js/03abab96.a07ccaca.js index 84f3a2b80..00889315c 100644 --- a/assets/js/03abab96.c0211075.js +++ b/assets/js/03abab96.a07ccaca.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4021],{83695:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>p,frontMatter:()=>o,metadata:()=>s,toc:()=>u});var n=i(58168),a=(i(96540),i(15680));i(67443);const o={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},r=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},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.yg)(d,(0,n.A)({},c,i,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,a.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,a.yg)("p",null,"Most of the time, your ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute 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.yg)("h2",{id:"sample"},"Sample"),(0,a.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,a.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,a.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,a.yg)("h2",{id:"best-practices"},"Best practices"),(0,a.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,a.yg)("pre",null,(0,a.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,a.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,a.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,a.yg)("pre",null,(0,a.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,a.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,a.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,a.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n')),(0,a.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,a.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,a.yg)("ul",null,(0,a.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,a.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,a.yg)("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.yg)("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([[4021],{83695:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>p,frontMatter:()=>o,metadata:()=>s,toc:()=>u});var n=i(58168),a=(i(96540),i(15680));i(67443);const o={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},r=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},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.yg)(d,(0,n.A)({},c,i,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,a.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,a.yg)("p",null,"Most of the time, your ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute 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.yg)("h2",{id:"sample"},"Sample"),(0,a.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,a.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,a.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,a.yg)("h2",{id:"best-practices"},"Best practices"),(0,a.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,a.yg)("pre",null,(0,a.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,a.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,a.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,a.yg)("pre",null,(0,a.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,a.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,a.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,a.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n')),(0,a.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,a.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,a.yg)("ul",null,(0,a.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,a.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,a.yg)("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.yg)("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/03c886f6.e5c176a5.js b/assets/js/03c886f6.579f399b.js similarity index 99% rename from assets/js/03c886f6.e5c176a5.js rename to assets/js/03c886f6.579f399b.js index aad0687ce..c41af02ea 100644 --- a/assets/js/03c886f6.e5c176a5.js +++ b/assets/js/03c886f6.579f399b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4827],{95454:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var t=n(58168),r=(n(96540),n(15680));n(67443);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-7.0.0/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-7.0.0/argument-resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/7.0.0/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/argument-resolving.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom annotations",permalink:"/docs/7.0.0/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/7.0.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},g="wrapper";function d(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},m,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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([[4827],{95454:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var t=n(58168),r=(n(96540),n(15680));n(67443);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-7.0.0/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-7.0.0/argument-resolving.md",sourceDirName:".",slug:"/argument-resolving",permalink:"/docs/7.0.0/argument-resolving",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/argument-resolving.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom annotations",permalink:"/docs/7.0.0/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/7.0.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},g="wrapper";function d(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},m,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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/04610919.db99bd1a.js b/assets/js/04610919.75bea3c5.js similarity index 98% rename from assets/js/04610919.db99bd1a.js rename to assets/js/04610919.75bea3c5.js index 6df5b6beb..8b715771b 100644 --- a/assets/js/04610919.db99bd1a.js +++ b/assets/js/04610919.75bea3c5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7107],{56396:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-8.0.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-8.0.0/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/semver.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Attributes reference",permalink:"/docs/annotations-reference"},next:{title:"Changelog",permalink:"/docs/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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([[7107],{56396:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-8.0.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-8.0.0/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/semver.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Attributes reference",permalink:"/docs/annotations-reference"},next:{title:"Changelog",permalink:"/docs/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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/05e8cfc0.a282a486.js b/assets/js/05e8cfc0.b3c9b9a7.js similarity index 98% rename from assets/js/05e8cfc0.a282a486.js rename to assets/js/05e8cfc0.b3c9b9a7.js index f4f237e2b..073405ffe 100644 --- a/assets/js/05e8cfc0.a282a486.js +++ b/assets/js/05e8cfc0.b3c9b9a7.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5091],{3716:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>y,frontMatter:()=>o,metadata:()=>i,toc:()=>u});var a=t(58168),r=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},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 y(e){let{components:n,...t}=e;return(0,r.yg)(d,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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."))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5091],{3716:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>y,frontMatter:()=>o,metadata:()=>i,toc:()=>u});var a=t(58168),r=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},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 y(e){let{components:n,...t}=e;return(0,r.yg)(d,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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."))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/05fed6b1.dc35b3f9.js b/assets/js/05fed6b1.d73b7c21.js similarity index 99% rename from assets/js/05fed6b1.dc35b3f9.js rename to assets/js/05fed6b1.d73b7c21.js index 61728338a..58710c2f1 100644 --- a/assets/js/05fed6b1.dc35b3f9.js +++ b/assets/js/05fed6b1.d73b7c21.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4620],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),g(e)}),[u,g,i]),tabValues:i}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function T(e){const t=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},24391:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),i=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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,...a}=e;return(0,r.yg)(h,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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([[4620],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),g(e)}),[u,g,i]),tabValues:i}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function T(e){const t=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},24391:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),i=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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,...a}=e;return(0,r.yg)(h,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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/06c02cc7.52e92924.js b/assets/js/06c02cc7.9e169703.js similarity index 98% rename from assets/js/06c02cc7.52e92924.js rename to assets/js/06c02cc7.9e169703.js index 362e968ca..2c675cded 100644 --- a/assets/js/06c02cc7.52e92924.js +++ b/assets/js/06c02cc7.9e169703.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4803],{75959:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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-7.0.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-7.0.0/universal-service-providers.md",sourceDirName:".",slug:"/universal-service-providers",permalink:"/docs/7.0.0/universal-service-providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/universal-service-providers.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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/7.0.0/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/7.0.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,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/7.0.0/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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([[4803],{75959:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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-7.0.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-7.0.0/universal-service-providers.md",sourceDirName:".",slug:"/universal-service-providers",permalink:"/docs/7.0.0/universal-service-providers",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/universal-service-providers.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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/7.0.0/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/7.0.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,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/7.0.0/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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/07623f9a.c14947dc.js b/assets/js/07623f9a.4dc114b5.js similarity index 99% rename from assets/js/07623f9a.c14947dc.js rename to assets/js/07623f9a.4dc114b5.js index 0b5fe5384..ab425f516 100644 --- a/assets/js/07623f9a.c14947dc.js +++ b/assets/js/07623f9a.4dc114b5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6925],{42562:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>o,default:()=>c,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=a(58168),r=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],y={toc:s},g="wrapper";function c(e){let{components:n,...a}=e;return(0,r.yg)(g,(0,t.A)({},y,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,r.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,r.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.yg)("p",null,"Now, go to the ",(0,r.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"config/packages/graphqlite.yaml")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,r.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,r.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,r.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"app/AppKernel.php")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>o,default:()=>c,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=a(58168),r=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],y={toc:s},g="wrapper";function c(e){let{components:n,...a}=e;return(0,r.yg)(g,(0,t.A)({},y,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,r.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,r.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.yg)("p",null,"Now, go to the ",(0,r.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"config/packages/graphqlite.yaml")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,r.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,r.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,r.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"app/AppKernel.php")),(0,r.yg)("pre",null,(0,r.yg)("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(58168),a=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,r.A)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("h2",{id:"the-problem"},"The problem"),(0,a.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,a.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,a.yg)("p",null,"A naive implementation will do this:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,a.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,a.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,a.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,a.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,a.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,a.yg)("p",null,"For instance:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("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([[2174],{69463:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>s,metadata:()=>i,toc:()=>h});var r=n(58168),a=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,r.A)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("h2",{id:"the-problem"},"The problem"),(0,a.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,a.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,a.yg)("p",null,"A naive implementation will do this:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,a.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,a.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,a.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,a.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,a.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,a.yg)("p",null,"For instance:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("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.a2553195.js b/assets/js/077a13b8.cd744d8f.js similarity index 99% rename from assets/js/077a13b8.a2553195.js rename to assets/js/077a13b8.cd744d8f.js index 05ba1db16..3b4fe2c09 100644 --- a/assets/js/077a13b8.a2553195.js +++ b/assets/js/077a13b8.cd744d8f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6986],{19365:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(96540),r=a(20053);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.A)(l.tabItem,i),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>x});var n=a(58168),r=a(96540),l=a(20053),i=a(23104),o=a(56347),u=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(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(!y({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,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return y({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),h(e)}),[s,h,l]),tabValues:l}}var f=a(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},y=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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:y,onClick:d},i,{className:(0,l.A)("tabs__item",g.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 T(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",g.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function x(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},24933:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/extend-type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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([[6986],{19365:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(96540),r=a(20053);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.A)(l.tabItem,i),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>x});var n=a(58168),r=a(96540),l=a(20053),i=a(23104),o=a(56347),u=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(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(!y({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,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return y({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),h(e)}),[s,h,l]),tabValues:l}}var f=a(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},y=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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:y,onClick:d},i,{className:(0,l.A)("tabs__item",g.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 T(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",g.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function x(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},24933:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/extend-type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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/079b0d3e.43598dd6.js b/assets/js/079b0d3e.8f199a77.js similarity index 99% rename from assets/js/079b0d3e.43598dd6.js rename to assets/js/079b0d3e.8f199a77.js index 8203906c1..6fe277ee8 100644 --- a/assets/js/079b0d3e.43598dd6.js +++ b/assets/js/079b0d3e.8f199a77.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2369],{19365:(e,n,t)=>{t.d(n,{A:()=>r});var a=t(96540),o=t(20053);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.A)(i.tabItem,r),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>A});var a=t(58168),o=t(96540),i=t(20053),r=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.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:o}}=e;return{value:n,label:t,attributes:a,default:o}}))}function d(e){const{values:n,children:t}=e;return(0,o.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 y(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,l.W6)(),i=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.aZ)(i),(0,o.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.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(!y({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:i}))),[u,s]=h({queryString:t,groupId:a}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,o.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),m=(()=>{const e=u??p;return y({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{m&&l(m)}),[m]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!y({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(p(n),u(a))},y=e=>{let n=null;switch(e.key){case"Enter":d(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 o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:r}=e;return o.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:y,onClick:d},r,{className:(0,i.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===n})}),t??n)})))}function T(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,o.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=g(e);return o.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},o.createElement(b,(0,a.A)({},e,n)),o.createElement(T,(0,a.A)({},e,n)))}function A(e){const n=(0,m.A)();return o.createElement(v,(0,a.A)({key:String(n)},e))}},91271:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>h,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=t(58168),o=(t(96540),t(15680)),i=(t(67443),t(11470)),r=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:n,...t}=e;return(0,o.yg)(y,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.yg)("p",null,"For instance:"),(0,o.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,o.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.yg)("p",null,"GraphQLite allows you to use a ",(0,o.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!")," The ",(0,o.yg)("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.yg)("br",null),(0,o.yg)("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.yg)("p",null,"In methods with a ",(0,o.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.yg)("h2",{id:"sourcefield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.yg)("p",null,"If you don't want to rewrite all ",(0,o.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("h2",{id:"magicfield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"Any annotations described in the ",(0,o.yg)("a",{parentName:"p",href:"/docs/6.0/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/6.0/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.yg)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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")))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2369],{19365:(e,n,t)=>{t.d(n,{A:()=>r});var a=t(96540),o=t(20053);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.A)(i.tabItem,r),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>A});var a=t(58168),o=t(96540),i=t(20053),r=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.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:o}}=e;return{value:n,label:t,attributes:a,default:o}}))}function d(e){const{values:n,children:t}=e;return(0,o.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 y(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,l.W6)(),i=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.aZ)(i),(0,o.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.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(!y({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:i}))),[u,s]=h({queryString:t,groupId:a}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,o.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),m=(()=>{const e=u??p;return y({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{m&&l(m)}),[m]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!y({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(p(n),u(a))},y=e=>{let n=null;switch(e.key){case"Enter":d(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 o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:r}=e;return o.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:y,onClick:d},r,{className:(0,i.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===n})}),t??n)})))}function T(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,o.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=g(e);return o.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},o.createElement(b,(0,a.A)({},e,n)),o.createElement(T,(0,a.A)({},e,n)))}function A(e){const n=(0,m.A)();return o.createElement(v,(0,a.A)({key:String(n)},e))}},91271:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>h,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=t(58168),o=(t(96540),t(15680)),i=(t(67443),t(11470)),r=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:n,...t}=e;return(0,o.yg)(y,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.yg)("p",null,"For instance:"),(0,o.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,o.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.yg)("p",null,"GraphQLite allows you to use a ",(0,o.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!")," The ",(0,o.yg)("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.yg)("br",null),(0,o.yg)("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.yg)("p",null,"In methods with a ",(0,o.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.yg)("h2",{id:"sourcefield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.yg)("p",null,"If you don't want to rewrite all ",(0,o.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("h2",{id:"magicfield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"Any annotations described in the ",(0,o.yg)("a",{parentName:"p",href:"/docs/6.0/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/6.0/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.yg)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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")))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/07c49ebd.a4bb9e2a.js b/assets/js/07c49ebd.142b8e9f.js similarity index 99% rename from assets/js/07c49ebd.a4bb9e2a.js rename to assets/js/07c49ebd.142b8e9f.js index 4742e6bd7..968c7df43 100644 --- a/assets/js/07c49ebd.a4bb9e2a.js +++ b/assets/js/07c49ebd.142b8e9f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8633],{37721:(e,n,i)=>{i.r(n),i.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var t=i(58168),a=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,t.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour\nof a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:i(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"OnlyDebug.php")),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:",(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"li"},"graphql.field_middleware")," tag.")))}c.isMDXComponent=!0},8643:(e,n,i)=>{i.d(n,{A:()=>t});const t=i.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8633],{37721:(e,n,i)=>{i.r(n),i.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var t=i(58168),a=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,t.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour\nof a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:i(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"OnlyDebug.php")),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:",(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"li"},"graphql.field_middleware")," tag.")))}c.isMDXComponent=!0},8643:(e,n,i)=>{i.d(n,{A:()=>t});const t=i.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/085c135f.62109324.js b/assets/js/085c135f.41ba6b03.js similarity index 99% rename from assets/js/085c135f.62109324.js rename to assets/js/085c135f.41ba6b03.js index 8060f7637..32529c636 100644 --- a/assets/js/085c135f.62109324.js +++ b/assets/js/085c135f.41ba6b03.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[362],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(l.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),l=a(20053),u=a(23104),o=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.W6)(),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.aZ)(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 h(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]=g({queryString:a,groupId:n}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);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),h(e)}),[i,h,l]),tabValues:l}}var b=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.tabItem,u?.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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(f,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function T(e){const t=(0,b.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},2993:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},p=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[362],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(l.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),l=a(20053),u=a(23104),o=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.W6)(),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.aZ)(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 h(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]=g({queryString:a,groupId:n}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);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),h(e)}),[i,h,l]),tabValues:l}}var b=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.tabItem,u?.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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(f,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function T(e){const t=(0,b.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},2993:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},p=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/08fe23a4.0c7fa6f6.js b/assets/js/08fe23a4.5847e977.js similarity index 96% rename from assets/js/08fe23a4.0c7fa6f6.js rename to assets/js/08fe23a4.5847e977.js index 4236f3237..511e961c8 100644 --- a/assets/js/08fe23a4.0c7fa6f6.js +++ b/assets/js/08fe23a4.5847e977.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[514],{65235:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>c,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(58168),i=(n(96540),n(15680));n(67443);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/6.1/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/mutations.mdx",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/6.1/queries"},next:{title:"Type mapping",permalink:"/docs/6.1/type-mapping"}},u={},d=[],l={toc:d},p="wrapper";function c(t){let{components:e,...n}=t;return(0,i.yg)(p,(0,a.A)({},l,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, mutations are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/6.1/queries"},"like queries"),"."),(0,i.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("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([[514],{65235:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>c,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(58168),i=(n(96540),n(15680));n(67443);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/6.1/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/mutations.mdx",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/6.1/queries"},next:{title:"Type mapping",permalink:"/docs/6.1/type-mapping"}},u={},d=[],l={toc:d},p="wrapper";function c(t){let{components:e,...n}=t;return(0,i.yg)(p,(0,a.A)({},l,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, mutations are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/6.1/queries"},"like queries"),"."),(0,i.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("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.ef16c98f.js b/assets/js/0a57d896.ae7e2a2c.js similarity index 99% rename from assets/js/0a57d896.ef16c98f.js rename to assets/js/0a57d896.ae7e2a2c.js index 25e04064e..cfb70cf6c 100644 --- a/assets/js/0a57d896.ef16c98f.js +++ b/assets/js/0a57d896.ae7e2a2c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7471],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>w});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),c=t(31682),u=t(89466);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,c.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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,c]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,u.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),c(e),y(e)}),[c,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),h=e=>{const n=e.currentTarget,t=u.indexOf(n),r=c[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=u.indexOf(e.currentTarget)+1;n=u[t]??u[0];break}case"ArrowLeft":{const t=u.indexOf(e.currentTarget)-1;n=u[t]??u[u.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.A)("tabs__item",f.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 v(e){const n=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function w(e){const n=(0,m.A)();return a.createElement(v,(0,r.A)({key:String(n)},e))}},18419:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>c,toc:()=>p});var r=t(58168),a=(t(96540),t(15680)),o=(t(67443),t(11470)),i=t(19365);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling",original_id:"error-handling"},s=void 0,c={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},u={},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 g(e){let{components:n,...t}=e;return(0,a.yg)(d,(0,r.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.1/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/4.1/laravel-package"},"Laravel"),")."),(0,a.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7471],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>w});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),c=t(31682),u=t(89466);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,c.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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,c]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,u.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),c(e),y(e)}),[c,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),h=e=>{const n=e.currentTarget,t=u.indexOf(n),r=c[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=u.indexOf(e.currentTarget)+1;n=u[t]??u[0];break}case"ArrowLeft":{const t=u.indexOf(e.currentTarget)-1;n=u[t]??u[u.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.A)("tabs__item",f.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 v(e){const n=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function w(e){const n=(0,m.A)();return a.createElement(v,(0,r.A)({key:String(n)},e))}},18419:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>c,toc:()=>p});var r=t(58168),a=(t(96540),t(15680)),o=(t(67443),t(11470)),i=t(19365);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling",original_id:"error-handling"},s=void 0,c={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},u={},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 g(e){let{components:n,...t}=e;return(0,a.yg)(d,(0,r.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.1/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/4.1/laravel-package"},"Laravel"),")."),(0,a.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0cb7e976.d95c0503.js b/assets/js/0cb7e976.58b0ec3b.js similarity index 99% rename from assets/js/0cb7e976.d95c0503.js rename to assets/js/0cb7e976.58b0ec3b.js index 647c3979b..23d400525 100644 --- a/assets/js/0cb7e976.d95c0503.js +++ b/assets/js/0cb7e976.58b0ec3b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8112],{17678:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>p,frontMatter:()=>r,metadata:()=>s,toc:()=>l});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},o=void 0,s={unversionedId:"fine-grained-security",id:"fine-grained-security",title:"Fine grained security",description:"If the #[Logged] and #[Right] attributes 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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},u={},l=[{value:"Using the #Security attribute",id:"using-the-security-attribute",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:l},g="wrapper";function p(e){let{components:t,...n}=e;return(0,i.yg)(g,(0,a.A)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"If the ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/authentication-authorization#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"#[Logged]")," and ",(0,i.yg)("inlineCode",{parentName:"a"},"#[Right]")," attributes")," are not\ngranular enough for your needs, you can use the advanced ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute."),(0,i.yg)("p",null,"Using the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute, you can write an ",(0,i.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,i.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,i.yg)("li",{parentName:"ul"},"...")),(0,i.yg)("h2",{id:"using-the-security-attribute"},"Using the #","[Security]"," attribute"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute must conform to ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,i.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,i.yg)("code",null,"#[Security]")," attribute. Most of the inspiration of this attribute comes from Symfony. Warning though! GraphQLite's ",(0,i.yg)("code",null,"#[Security]")," attribute and Symfony's ",(0,i.yg)("code",null,"#[Security]")," attribute are slightly different. Especially, the two attributes do not live in the same namespace!"),(0,i.yg)("h2",{id:"the-is_granted-function"},"The ",(0,i.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n")),(0,i.yg)("p",null,"is similar to"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n')),(0,i.yg)("p",null,"In addition, the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, the ",(0,i.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,i.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,i.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," expression."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security attribute purpose to do simple input validation."),(0,i.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/authentication-authorization#not-throwing-errors"},(0,i.yg)("inlineCode",{parentName:"a"},"#[FailWith]")," attribute"),"\nbut for a given ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute."),(0,i.yg)("p",null,"You cannot use the ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,i.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n')),(0,i.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute can be used in any query, mutation or field, so anywhere you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Mutation]"),"\nor ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute."),(0,i.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n")),(0,i.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,i.yg)("p",null,"If you are using Laravel, you will ",(0,i.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,i.yg)("p",null,"If you are using another framework, you need to know that the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,i.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8112],{17678:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>p,frontMatter:()=>r,metadata:()=>s,toc:()=>l});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},o=void 0,s={unversionedId:"fine-grained-security",id:"fine-grained-security",title:"Fine grained security",description:"If the #[Logged] and #[Right] attributes 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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},u={},l=[{value:"Using the #Security attribute",id:"using-the-security-attribute",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:l},g="wrapper";function p(e){let{components:t,...n}=e;return(0,i.yg)(g,(0,a.A)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"If the ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/authentication-authorization#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"#[Logged]")," and ",(0,i.yg)("inlineCode",{parentName:"a"},"#[Right]")," attributes")," are not\ngranular enough for your needs, you can use the advanced ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute."),(0,i.yg)("p",null,"Using the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute, you can write an ",(0,i.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,i.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,i.yg)("li",{parentName:"ul"},"...")),(0,i.yg)("h2",{id:"using-the-security-attribute"},"Using the #","[Security]"," attribute"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute must conform to ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,i.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,i.yg)("code",null,"#[Security]")," attribute. Most of the inspiration of this attribute comes from Symfony. Warning though! GraphQLite's ",(0,i.yg)("code",null,"#[Security]")," attribute and Symfony's ",(0,i.yg)("code",null,"#[Security]")," attribute are slightly different. Especially, the two attributes do not live in the same namespace!"),(0,i.yg)("h2",{id:"the-is_granted-function"},"The ",(0,i.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n")),(0,i.yg)("p",null,"is similar to"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n')),(0,i.yg)("p",null,"In addition, the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, the ",(0,i.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,i.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,i.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," expression."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security attribute purpose to do simple input validation."),(0,i.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/authentication-authorization#not-throwing-errors"},(0,i.yg)("inlineCode",{parentName:"a"},"#[FailWith]")," attribute"),"\nbut for a given ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute."),(0,i.yg)("p",null,"You cannot use the ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,i.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n')),(0,i.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute can be used in any query, mutation or field, so anywhere you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Mutation]"),"\nor ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute."),(0,i.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n")),(0,i.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,i.yg)("p",null,"If you are using Laravel, you will ",(0,i.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,i.yg)("p",null,"If you are using another framework, you need to know that the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,i.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0d7bb119.dc71c1b6.js b/assets/js/0d7bb119.a92797bd.js similarity index 98% rename from assets/js/0d7bb119.dc71c1b6.js rename to assets/js/0d7bb119.a92797bd.js index 5695f6283..8e5732362 100644 --- a/assets/js/0d7bb119.dc71c1b6.js +++ b/assets/js/0d7bb119.a92797bd.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5981],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>q});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),u=n(56347),s=n(57485),i=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&u(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}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":u===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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function q(e){const t=(0,y.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},8532:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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([[5981],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>q});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),u=n(56347),s=n(57485),i=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&u(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}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":u===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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function q(e){const t=(0,y.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},8532:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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.a3ed74ef.js b/assets/js/0db009bb.45448590.js similarity index 97% rename from assets/js/0db009bb.a3ed74ef.js rename to assets/js/0db009bb.45448590.js index 6096f7535..07cc41844 100644 --- a/assets/js/0db009bb.a3ed74ef.js +++ b/assets/js/0db009bb.45448590.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8028],{9:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:l},g="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,r.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8028],{9:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:l},g="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,r.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0db959c8.7a233fd1.js b/assets/js/0db959c8.87e96419.js similarity index 99% rename from assets/js/0db959c8.7a233fd1.js rename to assets/js/0db959c8.87e96419.js index b16fe060a..6ae517c3e 100644 --- a/assets/js/0db959c8.7a233fd1.js +++ b/assets/js/0db959c8.87e96419.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2227],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),r=n(20053);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.A)(o.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),o=n(20053),i=n(23104),l=n(56347),s=n(57485),u=n(31682),c=n(89466);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,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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,u]=m({queryString:n,groupId:a}),[p,h]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,c.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),y=(()=>{const e=s??p;return g({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(p(t),s(a))},g=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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},i,{className:(0,o.A)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(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 P(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",b.tabList)},r.createElement(f,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,y.A)();return r.createElement(P,(0,a.A)({key:String(t)},e))}},89518:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),o=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...n}=e;return(0,r.yg)(g,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"Please note that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("strong",null,"Heads up!"),(0,r.yg)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",null,"PhpStorm via the ",(0,r.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.yg)("li",null,"Eclipse via the ",(0,r.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.yg)("li",null,"Netbeans has native support")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.yg)("p",null,"The same code can be written this way:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.yg)("p",null,"They support the same attributes too."),(0,r.yg)("p",null,"A few notable differences:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.yg)("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.yg)("p",null,"Let's take an example with the ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/autowiring"},(0,r.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2227],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),r=n(20053);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.A)(o.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),o=n(20053),i=n(23104),l=n(56347),s=n(57485),u=n(31682),c=n(89466);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,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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,u]=m({queryString:n,groupId:a}),[p,h]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,c.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),y=(()=>{const e=s??p;return g({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(p(t),s(a))},g=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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},i,{className:(0,o.A)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(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 P(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",b.tabList)},r.createElement(f,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,y.A)();return r.createElement(P,(0,a.A)({key:String(t)},e))}},89518:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),o=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...n}=e;return(0,r.yg)(g,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"Please note that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("strong",null,"Heads up!"),(0,r.yg)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",null,"PhpStorm via the ",(0,r.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.yg)("li",null,"Eclipse via the ",(0,r.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.yg)("li",null,"Netbeans has native support")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.yg)("p",null,"The same code can be written this way:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.yg)("p",null,"They support the same attributes too."),(0,r.yg)("p",null,"A few notable differences:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.yg)("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.yg)("p",null,"Let's take an example with the ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/autowiring"},(0,r.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0df2ba32.d45e3652.js b/assets/js/0df2ba32.40734af9.js similarity index 98% rename from assets/js/0df2ba32.d45e3652.js rename to assets/js/0df2ba32.40734af9.js index 53e94c645..21080e69d 100644 --- a/assets/js/0df2ba32.d45e3652.js +++ b/assets/js/0df2ba32.40734af9.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2935],{79441:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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([[2935],{79441:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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.e4236bca.js b/assets/js/0e5befdb.a35881e8.js similarity index 99% rename from assets/js/0e5befdb.e4236bca.js rename to assets/js/0e5befdb.a35881e8.js index 11ee2cce4..98d7d1b8f 100644 --- a/assets/js/0e5befdb.e4236bca.js +++ b/assets/js/0e5befdb.a35881e8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[932],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),r=n(20053);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.A)(l.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>T});var a=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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=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(!g({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]=h({queryString:n,groupId:a}),[d,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),m=(()=>{const e=s??d;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({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 m=n(92303);const f={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.a_)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==o&&(d(t),s(a))},g=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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:p},i,{className:(0,l.A)("tabs__item",f.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 N(e){const t=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function T(e){const t=(0,m.A)();return r.createElement(N,(0,a.A)({key:String(t)},e))}},13814:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>p,frontMatter:()=>l,metadata:()=>o,toc:()=>u});var a=n(58168),r=(n(96540),n(15680));n(67443),n(11470),n(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"docs",previous:{title:"Autowiring services",permalink:"/docs/6.1/autowiring"},next:{title:"External type declaration",permalink:"/docs/6.1/external-type-declaration"}},s={},u=[],c={toc:u},d="wrapper";function p(e){let{components:t,...n}=e;return(0,r.yg)(d,(0,a.A)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Using ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Let's break this sample:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,r.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.yg)("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.yg)("p",null,'Using the "',(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.yg)("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([[932],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),r=n(20053);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.A)(l.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>T});var a=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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=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(!g({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]=h({queryString:n,groupId:a}),[d,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,l]=(0,c.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),m=(()=>{const e=s??d;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({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 m=n(92303);const f={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.a_)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==o&&(d(t),s(a))},g=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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:p},i,{className:(0,l.A)("tabs__item",f.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 N(e){const t=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function T(e){const t=(0,m.A)();return r.createElement(N,(0,a.A)({key:String(t)},e))}},13814:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>p,frontMatter:()=>l,metadata:()=>o,toc:()=>u});var a=n(58168),r=(n(96540),n(15680));n(67443),n(11470),n(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"docs",previous:{title:"Autowiring services",permalink:"/docs/6.1/autowiring"},next:{title:"External type declaration",permalink:"/docs/6.1/external-type-declaration"}},s={},u=[],c={toc:u},d="wrapper";function p(e){let{components:t,...n}=e;return(0,r.yg)(d,(0,a.A)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Using ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Let's break this sample:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,r.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.yg)("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.yg)("p",null,'Using the "',(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.yg)("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.74119e9a.js b/assets/js/0ef60658.f01d1130.js similarity index 99% rename from assets/js/0ef60658.74119e9a.js rename to assets/js/0ef60658.f01d1130.js index 72ad066fe..49e4a5213 100644 --- a/assets/js/0ef60658.74119e9a.js +++ b/assets/js/0ef60658.f01d1130.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9255],{19365:(e,n,t)=>{t.d(n,{A:()=>r});var a=t(96540),o=t(20053);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.A)(i.tabItem,r),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>A});var a=t(58168),o=t(96540),i=t(20053),r=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.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:o}}=e;return{value:n,label:t,attributes:a,default:o}}))}function d(e){const{values:n,children:t}=e;return(0,o.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 y(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,l.W6)(),i=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.aZ)(i),(0,o.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.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(!y({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:i}))),[u,s]=h({queryString:t,groupId:a}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,o.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),m=(()=>{const e=u??p;return y({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{m&&l(m)}),[m]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!y({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(p(n),u(a))},y=e=>{let n=null;switch(e.key){case"Enter":d(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 o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:r}=e;return o.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:y,onClick:d},r,{className:(0,i.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===n})}),t??n)})))}function T(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,o.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=g(e);return o.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},o.createElement(b,(0,a.A)({},e,n)),o.createElement(T,(0,a.A)({},e,n)))}function A(e){const n=(0,m.A)();return o.createElement(v,(0,a.A)({key:String(n)},e))}},84663:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>h,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=t(58168),o=(t(96540),t(15680)),i=(t(67443),t(11470)),r=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:n,...t}=e;return(0,o.yg)(y,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.yg)("p",null,"For instance:"),(0,o.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,o.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.yg)("p",null,"GraphQLite allows you to use a ",(0,o.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!")," The ",(0,o.yg)("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.yg)("br",null),(0,o.yg)("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.yg)("p",null,"In methods with a ",(0,o.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.yg)("h2",{id:"sourcefield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.yg)("p",null,"If you don't want to rewrite all ",(0,o.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.yg)("h2",{id:"magicfield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"Any annotations described in the ",(0,o.yg)("a",{parentName:"p",href:"/docs/4.2/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/4.2/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.yg)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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")))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9255],{19365:(e,n,t)=>{t.d(n,{A:()=>r});var a=t(96540),o=t(20053);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.A)(i.tabItem,r),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>A});var a=t(58168),o=t(96540),i=t(20053),r=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.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:o}}=e;return{value:n,label:t,attributes:a,default:o}}))}function d(e){const{values:n,children:t}=e;return(0,o.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 y(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,l.W6)(),i=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.aZ)(i),(0,o.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.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(!y({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:i}))),[u,s]=h({queryString:t,groupId:a}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,o.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),m=(()=>{const e=u??p;return y({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{m&&l(m)}),[m]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!y({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(p(n),u(a))},y=e=>{let n=null;switch(e.key){case"Enter":d(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 o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:r}=e;return o.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:y,onClick:d},r,{className:(0,i.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===n})}),t??n)})))}function T(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,o.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=g(e);return o.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},o.createElement(b,(0,a.A)({},e,n)),o.createElement(T,(0,a.A)({},e,n)))}function A(e){const n=(0,m.A)();return o.createElement(v,(0,a.A)({key:String(n)},e))}},84663:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>h,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=t(58168),o=(t(96540),t(15680)),i=(t(67443),t(11470)),r=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:n,...t}=e;return(0,o.yg)(y,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.yg)("p",null,"For instance:"),(0,o.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,o.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.yg)("p",null,"GraphQLite allows you to use a ",(0,o.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!")," The ",(0,o.yg)("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.yg)("br",null),(0,o.yg)("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.yg)("p",null,"In methods with a ",(0,o.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.yg)("h2",{id:"sourcefield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.yg)("p",null,"If you don't want to rewrite all ",(0,o.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.yg)("h2",{id:"magicfield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"Any annotations described in the ",(0,o.yg)("a",{parentName:"p",href:"/docs/4.2/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/4.2/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.yg)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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")))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0fd21208.44507640.js b/assets/js/0fd21208.7331e278.js similarity index 96% rename from assets/js/0fd21208.44507640.js rename to assets/js/0fd21208.7331e278.js index 4c6e6e68f..ded8be621 100644 --- a/assets/js/0fd21208.44507640.js +++ b/assets/js/0fd21208.7331e278.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6158],{82188:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>c,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,a.A)({},l,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, mutations are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/queries"},"like queries"),"."),(0,i.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("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([[6158],{82188:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>c,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,a.A)({},l,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, mutations are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/queries"},"like queries"),"."),(0,i.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("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.140e06b8.js b/assets/js/102de343.7ec5ba9d.js similarity index 99% rename from assets/js/102de343.140e06b8.js rename to assets/js/102de343.7ec5ba9d.js index 935238c63..b811a19dc 100644 --- a/assets/js/102de343.140e06b8.js +++ b/assets/js/102de343.7ec5ba9d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9097],{26348:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>m});var t=a(58168),r=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:n,...a}=e;return(0,r.yg)(g,(0,t.A)({},p,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"li"},"ResolveInfo")," object. For instance:",(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"li"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware"))),(0,r.yg)("li",{parentName:"ul"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,r.yg)("li",{parentName:"ul"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Validate")," annotation (in Laravel package)")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middleware class")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter resolver class")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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([[9097],{26348:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>m});var t=a(58168),r=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:n,...a}=e;return(0,r.yg)(g,(0,t.A)({},p,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"li"},"ResolveInfo")," object. For instance:",(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"li"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware"))),(0,r.yg)("li",{parentName:"ul"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,r.yg)("li",{parentName:"ul"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Validate")," annotation (in Laravel package)")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middleware class")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter resolver class")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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/107b7a36.81035d33.js b/assets/js/107b7a36.702ad825.js similarity index 98% rename from assets/js/107b7a36.81035d33.js rename to assets/js/107b7a36.702ad825.js index 420372230..225f630fe 100644 --- a/assets/js/107b7a36.81035d33.js +++ b/assets/js/107b7a36.702ad825.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6408],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>q});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),u=n(56347),s=n(57485),i=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&u(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}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":u===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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function q(e){const t=(0,y.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},89316:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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([[6408],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>q});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),u=n(56347),s=n(57485),i=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&u(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}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":u===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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function q(e){const t=(0,y.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},89316:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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.6d0f76ea.js b/assets/js/107d11ee.7808e72a.js similarity index 98% rename from assets/js/107d11ee.6d0f76ea.js rename to assets/js/107d11ee.7808e72a.js index 80a6a2b8a..be4d17031 100644 --- a/assets/js/107d11ee.6d0f76ea.js +++ b/assets/js/107d11ee.7808e72a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6473],{32626:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/6.0/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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([[6473],{32626:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/6.0/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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/12d3ef9e.8e115802.js b/assets/js/12d3ef9e.a1c01304.js similarity index 99% rename from assets/js/12d3ef9e.8e115802.js rename to assets/js/12d3ef9e.a1c01304.js index 585d4c384..0b277e75e 100644 --- a/assets/js/12d3ef9e.8e115802.js +++ b/assets/js/12d3ef9e.a1c01304.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7042],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var a=t(96540),r=t(20053);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.A)(l.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),r=t(96540),l=t(20053),i=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);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.X)(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 g(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,o.W6)(),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.aZ)(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 y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=d(e),[i,o]=(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(!g({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,p.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),m=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const n=e.currentTarget,t=p.indexOf(n),a=u[t].value;a!==o&&(c(n),s(a))},g=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,l.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(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 T(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(n)},e))}},39972:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),i=t(19365);const o={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},s=void 0,u={unversionedId:"extend-type",id:"version-7.0.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-7.0.0/extend-type.mdx",sourceDirName:".",slug:"/extend-type",permalink:"/docs/7.0.0/extend-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/extend-type.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"docs",previous:{title:"Autowiring services",permalink:"/docs/7.0.0/autowiring"},next:{title:"External type declaration",permalink:"/docs/7.0.0/external-type-declaration"}},p={},c=[],d={toc:c},g="wrapper";function h(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Using ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Let's break this sample:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.yg)("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.yg)("p",null,'Using the "',(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7042],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var a=t(96540),r=t(20053);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.A)(l.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),r=t(96540),l=t(20053),i=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);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.X)(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 g(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,o.W6)(),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.aZ)(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 y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=d(e),[i,o]=(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(!g({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,p.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),m=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const n=e.currentTarget,t=p.indexOf(n),a=u[t].value;a!==o&&(c(n),s(a))},g=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,l.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(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 T(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(n)},e))}},39972:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),i=t(19365);const o={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},s=void 0,u={unversionedId:"extend-type",id:"version-7.0.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-7.0.0/extend-type.mdx",sourceDirName:".",slug:"/extend-type",permalink:"/docs/7.0.0/extend-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/extend-type.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},sidebar:"docs",previous:{title:"Autowiring services",permalink:"/docs/7.0.0/autowiring"},next:{title:"External type declaration",permalink:"/docs/7.0.0/external-type-declaration"}},p={},c=[],d={toc:c},g="wrapper";function h(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Using ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Let's break this sample:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.yg)("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.yg)("p",null,'Using the "',(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/136c1ee9.c64b8dee.js b/assets/js/136c1ee9.09b72467.js similarity index 99% rename from assets/js/136c1ee9.c64b8dee.js rename to assets/js/136c1ee9.09b72467.js index a46e3f058..1cdafd754 100644 --- a/assets/js/136c1ee9.c64b8dee.js +++ b/assets/js/136c1ee9.09b72467.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6086],{19365:(e,a,t)=>{t.d(a,{A:()=>o});var n=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:a,hidden:t,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>V});var n=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),s=t(57485),u=t(31682),d=t(89466);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function c(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??p(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function m(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:t}=e;const n=(0,l.W6)(),i=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const a=new URLSearchParams(n.location.search);a.set(i,e),n.replace({...n.location,search:a.toString()})}),[i,n])]}function y(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!m({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:i}))),[s,u]=h({queryString:t,groupId:n}),[p,y]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,i]=(0,d.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:n}),g=(()=>{const e=s??p;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),y(e)}),[u,y,i]),tabValues:i}}var g=t(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:a,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),c=e=>{const a=e.currentTarget,t=d.indexOf(a),n=u[t].value;n!==l&&(p(a),s(n))},m=e=>{let a=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const t=d.indexOf(e.currentTarget)+1;a=d[t]??d[0];break}case"ArrowLeft":{const t=d.indexOf(e.currentTarget)-1;a=d[t]??d[d.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.A)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=y(e);return r.createElement("div",{className:(0,i.A)("tabs-container",v.tabList)},r.createElement(f,(0,n.A)({},e,a)),r.createElement(b,(0,n.A)({},e,a)))}function V(e){const a=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},17317:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,r.yg)(m,(0,n.A)({},c,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,r.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.yg)("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.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.yg)("p",null,"You can also pass an array to the ",(0,r.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.yg)("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([[6086],{19365:(e,a,t)=>{t.d(a,{A:()=>o});var n=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:a,hidden:t,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>V});var n=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),s=t(57485),u=t(31682),d=t(89466);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function c(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??p(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function m(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:t}=e;const n=(0,l.W6)(),i=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const a=new URLSearchParams(n.location.search);a.set(i,e),n.replace({...n.location,search:a.toString()})}),[i,n])]}function y(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!m({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:i}))),[s,u]=h({queryString:t,groupId:n}),[p,y]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,i]=(0,d.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:n}),g=(()=>{const e=s??p;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),y(e)}),[u,y,i]),tabValues:i}}var g=t(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:a,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),c=e=>{const a=e.currentTarget,t=d.indexOf(a),n=u[t].value;n!==l&&(p(a),s(n))},m=e=>{let a=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const t=d.indexOf(e.currentTarget)+1;a=d[t]??d[0];break}case"ArrowLeft":{const t=d.indexOf(e.currentTarget)-1;a=d[t]??d[d.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.A)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=y(e);return r.createElement("div",{className:(0,i.A)("tabs-container",v.tabList)},r.createElement(f,(0,n.A)({},e,a)),r.createElement(b,(0,n.A)({},e,a)))}function V(e){const a=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},17317:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,r.yg)(m,(0,n.A)({},c,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,r.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.yg)("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.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.yg)("p",null,"You can also pass an array to the ",(0,r.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.yg)("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.58680537.js b/assets/js/13b4aeb1.853bf41f.js similarity index 98% rename from assets/js/13b4aeb1.58680537.js rename to assets/js/13b4aeb1.853bf41f.js index 6a31808ff..18d6b8a45 100644 --- a/assets/js/13b4aeb1.58680537.js +++ b/assets/js/13b4aeb1.853bf41f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6088],{43799:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>o,metadata:()=>r,toc:()=>p});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,n.A)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,i.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,i.yg)("h2",{id:"usage"},"Usage"),(0,i.yg)("p",null,"In your query, simply return a class that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Notice that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,i.yg)("li",{parentName:"ul"},"you MUST add a ",(0,i.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,i.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,i.yg)("p",null,'The "count" field returns the ',(0,i.yg)("strong",{parentName:"p"},"total count")," of items."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6088],{43799:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>o,metadata:()=>r,toc:()=>p});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,n.A)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,i.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,i.yg)("h2",{id:"usage"},"Usage"),(0,i.yg)("p",null,"In your query, simply return a class that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Notice that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,i.yg)("li",{parentName:"ul"},"you MUST add a ",(0,i.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,i.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,i.yg)("p",null,'The "count" field returns the ',(0,i.yg)("strong",{parentName:"p"},"total count")," of items."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1428bdad.5f092d25.js b/assets/js/1428bdad.e9676a5b.js similarity index 99% rename from assets/js/1428bdad.5f092d25.js rename to assets/js/1428bdad.e9676a5b.js index 33bddb9ae..8e4f8d860 100644 --- a/assets/js/1428bdad.5f092d25.js +++ b/assets/js/1428bdad.e9676a5b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3723],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),s=a(57485),i=a(31682),u=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=s??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const u=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},46618:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>y,frontMatter:()=>p,metadata:()=>l,toc:()=>i});var n=a(58168),r=(a(96540),a(15680));a(67443),a(11470),a(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/6.1/pagination"},next:{title:"Custom annotations",permalink:"/docs/6.1/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.yg)(c,(0,n.A)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n')),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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([[3723],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),s=a(57485),i=a(31682),u=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=s??c;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:i}=e;const u=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},46618:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>y,frontMatter:()=>p,metadata:()=>l,toc:()=>i});var n=a(58168),r=(a(96540),a(15680));a(67443),a(11470),a(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/6.1/pagination"},next:{title:"Custom annotations",permalink:"/docs/6.1/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.yg)(c,(0,n.A)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n')),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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.4bece173.js b/assets/js/143f7888.7046ae9e.js similarity index 99% rename from assets/js/143f7888.4bece173.js rename to assets/js/143f7888.7046ae9e.js index 6b3682f2b..1a3f291ec 100644 --- a/assets/js/143f7888.4bece173.js +++ b/assets/js/143f7888.7046ae9e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5198],{16733:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/4.1/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/4.1/annotations_reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5198],{16733:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/4.1/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/4.1/annotations_reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/15a79915.03cabaec.js b/assets/js/15a79915.ba618513.js similarity index 99% rename from assets/js/15a79915.03cabaec.js rename to assets/js/15a79915.ba618513.js index ad52eb143..8100716a0 100644 --- a/assets/js/15a79915.03cabaec.js +++ b/assets/js/15a79915.ba618513.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6729],{19365:(e,a,t)=>{t.d(a,{A:()=>i});var n=t(96540),r=t(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:a,hidden:t,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),l=t(20053),i=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function d(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function g(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:t}=e;const n=(0,o.W6)(),l=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(n.location.search);a.set(l,e),n.replace({...n.location,search:a.toString()})}),[l,n])]}function m(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:l}))),[s,u]=h({queryString:t,groupId:n}),[c,m]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,l]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:n}),y=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,l]),tabValues:l}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==o&&(c(a),s(n))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,a)),r.createElement(b,(0,n.A)({},e,a)))}function T(e){const a=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},40470:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),i=t(19365);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-7.0.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-7.0.0/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/7.0.0/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/laravel-package-advanced.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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/7.0.0/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/7.0.0/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},g="wrapper";function h(e){let{components:a,...t}=e;return(0,r.yg)(g,(0,n.A)({},d,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"export-the-schema-from-the-cli"},"Export the schema from the CLI"),(0,r.yg)("p",null,"The extension comes with a special command: ",(0,r.yg)("inlineCode",{parentName:"p"},"graphqlite:export-schema"),"."),(0,r.yg)("p",null,"Usage:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ ./artisan graphqlite:export-schema --output=schema.graphql\n")),(0,r.yg)("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)."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6729],{19365:(e,a,t)=>{t.d(a,{A:()=>i});var n=t(96540),r=t(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:a,hidden:t,className:i}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),l=t(20053),i=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function d(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function g(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:t}=e;const n=(0,o.W6)(),l=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(n.location.search);a.set(l,e),n.replace({...n.location,search:a.toString()})}),[l,n])]}function m(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:l}))),[s,u]=h({queryString:t,groupId:n}),[c,m]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,l]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:n}),y=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,l]),tabValues:l}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==o&&(c(a),s(n))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,a)),r.createElement(b,(0,n.A)({},e,a)))}function T(e){const a=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},40470:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),i=t(19365);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-7.0.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-7.0.0/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/7.0.0/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/laravel-package-advanced.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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/7.0.0/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/7.0.0/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},g="wrapper";function h(e){let{components:a,...t}=e;return(0,r.yg)(g,(0,n.A)({},d,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"export-the-schema-from-the-cli"},"Export the schema from the CLI"),(0,r.yg)("p",null,"The extension comes with a special command: ",(0,r.yg)("inlineCode",{parentName:"p"},"graphqlite:export-schema"),"."),(0,r.yg)("p",null,"Usage:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ ./artisan graphqlite:export-schema --output=schema.graphql\n")),(0,r.yg)("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)."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/15b5a907.a1750297.js b/assets/js/15b5a907.3862c567.js similarity index 99% rename from assets/js/15b5a907.a1750297.js rename to assets/js/15b5a907.3862c567.js index a2a6ca8a1..d9935b01a 100644 --- a/assets/js/15b5a907.a1750297.js +++ b/assets/js/15b5a907.3862c567.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8023],{16871:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"version-7.0.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-7.0.0/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/7.0.0/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/laravel-package.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"docs",previous:{title:"Symfony bundle",permalink:"/docs/7.0.0/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/7.0.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}],g={toc:s},h="wrapper";function u(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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([[8023],{16871:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"version-7.0.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-7.0.0/laravel-package.md",sourceDirName:".",slug:"/laravel-package",permalink:"/docs/7.0.0/laravel-package",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/laravel-package.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"docs",previous:{title:"Symfony bundle",permalink:"/docs/7.0.0/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/7.0.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}],g={toc:s},h="wrapper";function u(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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/16017aa6.9376b16b.js b/assets/js/16017aa6.eadedf44.js similarity index 99% rename from assets/js/16017aa6.9376b16b.js rename to assets/js/16017aa6.eadedf44.js index 39cab721e..aec53115e 100644 --- a/assets/js/16017aa6.9376b16b.js +++ b/assets/js/16017aa6.eadedf44.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4366],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),l=n(20053);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.A)(r.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>T});var a=n(58168),l=n(96540),r=n(20053),i=n(23104),o=n(56347),u=n(57485),p=n(31682),s=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function g(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.W6)(),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.aZ)(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 m(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(!y({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]=g({queryString:n,groupId:a}),[c,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Dv)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),h=(()=>{const e=u??c;return y({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),m(e)}),[p,m,r]),tabValues:r}}var h=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},y=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.A)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},i,{className:(0,r.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(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 I(e){const t=m(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,t)),l.createElement(v,(0,a.A)({},e,t)))}function T(e){const t=(0,h.A)();return l.createElement(I,(0,a.A)({key:String(t)},e))}},62503:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>g,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(58168),l=(n(96540),n(15680)),r=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function g(e){let{components:t,...n}=e;return(0,l.yg)(y,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.yg)("p",null,"Your GraphQL query might look like this:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,l.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using ",(0,l.yg)("strong",{parentName:"p"},"Factory")," or annotating the class with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input"),"."),(0,l.yg)("h2",{id:"factory"},"Factory"),(0,l.yg)("p",null,"A ",(0,l.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.yg)("p",null,"Here is an example of factory:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.yg)("p",null,"A few important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.yg)("p",null,"You can use the ",(0,l.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.yg)("p",null,"Here is an annotated sample:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("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.yg)("p",null,"Image your ",(0,l.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"With the ",(0,l.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.yg)("p",null,"To be able to hide an argument, the argument must have a default value."),(0,l.yg)("h2",{id:"input-annotation"},"@Input Annotation"),(0,l.yg)("p",null,"Let's transform ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," class into an input type by adding ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation to it and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to corresponding properties:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"Now if you call ",(0,l.yg)("inlineCode",{parentName:"p"},"getCities()")," query you can pass the location input in the same way as with factories.\nThe ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with provided ",(0,l.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.yg)("inlineCode",{parentName:"p"},"longitude")," and passed to the controller as a parameter."),(0,l.yg)("p",null,"There are some important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized only on properties for Input Type."),(0,l.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.yg)("ul",{parentName:"li"},(0,l.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort."),(0,l.yg)("li",{parentName:"ul"},"For private or protected properties implemented public setter is required (if they are not set via constructor). For example ",(0,l.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),".")))),(0,l.yg)("h3",{id:"multiple-input-types-per-one-class"},"Multiple input types per one class"),(0,l.yg)("p",null,"Simple usage of ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"There are 2 input types created for just one class: ",(0,l.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.yg)("p",null,"Note that ",(0,l.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.yg)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.yg)("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."))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4366],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),l=n(20053);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.A)(r.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>T});var a=n(58168),l=n(96540),r=n(20053),i=n(23104),o=n(56347),u=n(57485),p=n(31682),s=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function g(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.W6)(),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.aZ)(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 m(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(!y({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]=g({queryString:n,groupId:a}),[c,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Dv)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),h=(()=>{const e=u??c;return y({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),m(e)}),[p,m,r]),tabValues:r}}var h=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},y=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.A)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},i,{className:(0,r.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(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 I(e){const t=m(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,t)),l.createElement(v,(0,a.A)({},e,t)))}function T(e){const t=(0,h.A)();return l.createElement(I,(0,a.A)({key:String(t)},e))}},62503:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>g,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(58168),l=(n(96540),n(15680)),r=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function g(e){let{components:t,...n}=e;return(0,l.yg)(y,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.yg)("p",null,"Your GraphQL query might look like this:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,l.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using ",(0,l.yg)("strong",{parentName:"p"},"Factory")," or annotating the class with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input"),"."),(0,l.yg)("h2",{id:"factory"},"Factory"),(0,l.yg)("p",null,"A ",(0,l.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.yg)("p",null,"Here is an example of factory:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.yg)("p",null,"A few important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.yg)("p",null,"You can use the ",(0,l.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.yg)("p",null,"Here is an annotated sample:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("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.yg)("p",null,"Image your ",(0,l.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"With the ",(0,l.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.yg)("p",null,"To be able to hide an argument, the argument must have a default value."),(0,l.yg)("h2",{id:"input-annotation"},"@Input Annotation"),(0,l.yg)("p",null,"Let's transform ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," class into an input type by adding ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation to it and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to corresponding properties:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"Now if you call ",(0,l.yg)("inlineCode",{parentName:"p"},"getCities()")," query you can pass the location input in the same way as with factories.\nThe ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with provided ",(0,l.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.yg)("inlineCode",{parentName:"p"},"longitude")," and passed to the controller as a parameter."),(0,l.yg)("p",null,"There are some important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized only on properties for Input Type."),(0,l.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.yg)("ul",{parentName:"li"},(0,l.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort."),(0,l.yg)("li",{parentName:"ul"},"For private or protected properties implemented public setter is required (if they are not set via constructor). For example ",(0,l.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),".")))),(0,l.yg)("h3",{id:"multiple-input-types-per-one-class"},"Multiple input types per one class"),(0,l.yg)("p",null,"Simple usage of ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"There are 2 input types created for just one class: ",(0,l.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.yg)("p",null,"Note that ",(0,l.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.yg)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.yg)("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."))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/16565e6a.70e7214b.js b/assets/js/16565e6a.7840e1d0.js similarity index 99% rename from assets/js/16565e6a.70e7214b.js rename to assets/js/16565e6a.7840e1d0.js index a4bf8e3a3..7abc0399b 100644 --- a/assets/js/16565e6a.70e7214b.js +++ b/assets/js/16565e6a.7840e1d0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3962],{96546:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>m});var t=a(58168),r=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function u(e){let{components:n,...a}=e;return(0,r.yg)(g,(0,t.A)({},p,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"li"},"ResolveInfo")," object. For instance:",(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"li"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware"))),(0,r.yg)("li",{parentName:"ul"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,r.yg)("li",{parentName:"ul"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Validate")," annotation (in Laravel package)")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middleware class")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter resolver class")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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([[3962],{96546:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>m});var t=a(58168),r=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function u(e){let{components:n,...a}=e;return(0,r.yg)(g,(0,t.A)({},p,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"li"},"ResolveInfo")," object. For instance:",(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"li"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware"))),(0,r.yg)("li",{parentName:"ul"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,r.yg)("li",{parentName:"ul"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Validate")," annotation (in Laravel package)")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middleware class")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter resolver class")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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/17518879.a0c1a1bd.js b/assets/js/17518879.4eba4643.js similarity index 99% rename from assets/js/17518879.a0c1a1bd.js rename to assets/js/17518879.4eba4643.js index 830d6206e..85542d011 100644 --- a/assets/js/17518879.a0c1a1bd.js +++ b/assets/js/17518879.4eba4643.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8873],{68523:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>d,contentTitle:()=>r,default:()=>u,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var t=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function u(e){let{components:a,...n}=e;return(0,i.yg)(g,(0,t.A)({},s,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"430"},"4.3.0"),(0,i.yg)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The method ",(0,i.yg)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.yg)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.yg)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.yg)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h4",{id:"new-features"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/input-types#input-annotation"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h4",{id:"new-features-1"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h4",{id:"new-features-2"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("h4",{id:"symfony"},"Symfony:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h4",{id:"laravel"},"Laravel:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h4",{id:"internals"},"Internals:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8873],{68523:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>d,contentTitle:()=>r,default:()=>u,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var t=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function u(e){let{components:a,...n}=e;return(0,i.yg)(g,(0,t.A)({},s,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"430"},"4.3.0"),(0,i.yg)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The method ",(0,i.yg)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.yg)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.yg)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.yg)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h4",{id:"new-features"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/input-types#input-annotation"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h4",{id:"new-features-1"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h4",{id:"new-features-2"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("h4",{id:"symfony"},"Symfony:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h4",{id:"laravel"},"Laravel:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.3/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h4",{id:"internals"},"Internals:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/17cca601.1d79c6ae.js b/assets/js/17cca601.2aca0642.js similarity index 99% rename from assets/js/17cca601.1d79c6ae.js rename to assets/js/17cca601.2aca0642.js index 812a81b23..b1cfcf83e 100644 --- a/assets/js/17cca601.1d79c6ae.js +++ b/assets/js/17cca601.2aca0642.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6053],{90333:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>r,default:()=>g,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var t=a(58168),i=(a(96540),a(15680));a(67443);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"version-7.0.0/changelog",title:"Changelog",description:"7.0.0",source:"@site/versioned_docs/version-7.0.0/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/7.0.0/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/CHANGELOG.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/7.0.0/semver"}},p={},s=[{value:"7.0.0",id:"700",level:2},{value:"Breaking Changes",id:"breaking-changes",level:3},{value:"New Features",id:"new-features",level:3},{value:"Improvements",id:"improvements",level:3},{value:"Minor Changes",id:"minor-changes",level:3},{value:"6.2.3",id:"623",level:2},{value:"6.2.2",id:"622",level:2},{value:"6.2.1",id:"621",level:2},{value:"6.2.0",id:"620",level:2},{value:"6.1.0",id:"610",level:2},{value:"Breaking Changes",id:"breaking-changes-1",level:3},{value:"Improvements",id:"improvements-1",level:3},{value:"5.0.0",id:"500",level:2},{value:"Dependencies",id:"dependencies",level:3},{value:"4.3.0",id:"430",level:2},{value:"Breaking change",id:"breaking-change",level:3},{value:"Minor changes",id:"minor-changes-1",level:3},{value:"4.2.0",id:"420",level:2},{value:"Breaking change",id:"breaking-change-1",level:3},{value:"New features",id:"new-features-1",level:3},{value:"4.1.0",id:"410",level:2},{value:"Breaking change",id:"breaking-change-2",level:3},{value:"New features",id:"new-features-2",level:3},{value:"Minor changes",id:"minor-changes-2",level:3},{value:"Miscellaneous",id:"miscellaneous",level:3},{value:"4.0.0",id:"400",level:2},{value:"New features",id:"new-features-3",level:3},{value:"Symfony",id:"symfony",level:3},{value:"Laravel",id:"laravel",level:3},{value:"Internals",id:"internals",level:3}],d={toc:s},u="wrapper";function g(e){let{components:n,...a}=e;return(0,i.yg)(u,(0,t.A)({},d,a,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"700"},"7.0.0"),(0,i.yg)("h3",{id:"breaking-changes"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#664 Replaces ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/class-explorer"},"thecodingmachine/class-explorer")," with ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/alekitto/class-finder"},"kcs/class-finder")," resulting in the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setClassNameMapper")," being renamed to ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setFinder"),". This now expects an instance of ",(0,i.yg)("inlineCode",{parentName:"li"},"Kcs\\ClassFinder\\Finder")," instead of ",(0,i.yg)("inlineCode",{parentName:"li"},"Kcs\\ClassFinder\\Finder\\FinderInterface"),". @fogrye")),(0,i.yg)("h3",{id:"new-features"},"New Features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#649 Adds support for ",(0,i.yg)("inlineCode",{parentName:"li"},"subscription")," operations. @oojacoboo"),(0,i.yg)("li",{parentName:"ul"},"#612 Automatic query complexity analysis. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#611 Automatic persisted queries. @oprypkhantc")),(0,i.yg)("h3",{id:"improvements"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#658 Improves on prefetching for nested fields. @grynchuk"),(0,i.yg)("li",{parentName:"ul"},"#646 Improves exception handling during schema parsing. @fogrye"),(0,i.yg)("li",{parentName:"ul"},"#636 Allows the use of middleware on construtor params/fields. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#623 Improves support for description arguments on types/fields. @downace"),(0,i.yg)("li",{parentName:"ul"},"#628 Properly handles ",(0,i.yg)("inlineCode",{parentName:"li"},"@param")," annotations for generics support on field annotated constructor arguments. @oojacoboo"),(0,i.yg)("li",{parentName:"ul"},"#584 Immutability improvements across the codebase. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#588 Prefetch improvements. @oprpkhantc"),(0,i.yg)("li",{parentName:"ul"},"#606 Adds support for phpdoc descriptions and deprecation annotations on native enums. @mdoelker"),(0,i.yg)("li",{parentName:"ul"},"Thanks to @shish, @cvergne and @mshapovalov for updating the docs!")),(0,i.yg)("h3",{id:"minor-changes"},"Minor Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#639 Added support for Symfony 7. @janatjak")),(0,i.yg)("h2",{id:"623"},"6.2.3"),(0,i.yg)("p",null,"Adds support for ",(0,i.yg)("inlineCode",{parentName:"p"},"Psr\\Container")," 1.1 with #601"),(0,i.yg)("h2",{id:"622"},"6.2.2"),(0,i.yg)("p",null,"This is a very simple release. We support Doctrine annotation 1.x and we've deprecated ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory::setDoctrineAnnotationReader")," in favor of native PHP attributes."),(0,i.yg)("h2",{id:"621"},"6.2.1"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Added support for new ",(0,i.yg)("inlineCode",{parentName:"li"},"Void")," return types, allowing use of ",(0,i.yg)("inlineCode",{parentName:"li"},"void")," from operation resolvers. #574"),(0,i.yg)("li",{parentName:"ul"},"Improvements with authorization middleware #571"),(0,i.yg)("li",{parentName:"ul"},"Updated vendor dependencies: #580 #558")),(0,i.yg)("h2",{id:"620"},"6.2.0"),(0,i.yg)("p",null,"Lots of little nuggets in this release! We're now targeting PHP ^8.1 and have testing on 8.2."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Better support for union types and enums: #530, #535, #561, #570"),(0,i.yg)("li",{parentName:"ul"},"Various bug and interface fixes: #532, #575, #564"),(0,i.yg)("li",{parentName:"ul"},"GraphQL v15 required: #542"),(0,i.yg)("li",{parentName:"ul"},"Lots of codebase improvements, more strict typing: #548")),(0,i.yg)("p",null,"A special thanks to @rusted-love and @oprypkhantc for their contributions."),(0,i.yg)("h2",{id:"610"},"6.1.0"),(0,i.yg)("p",null,"A shoutout to @bladl for his work on this release, improving the code for better typing and PHP 8.0 syntax updates!"),(0,i.yg)("h3",{id:"breaking-changes-1"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#518 PSR-11 support now requires version 2"),(0,i.yg)("li",{parentName:"ul"},"#508 Due to some of the code improvements, additional typing has been added to some interfaces/classes. For instance, ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface::toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface::toGraphQLInputType")," now have the following signatures:")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"}," /**\n * @param (OutputType&GraphQLType)|null $subType\n *\n * @return OutputType&GraphQLType\n */\n public function toGraphQLOutputType(\n Type $type,\n OutputType|null $subType,\n ReflectionMethod|ReflectionProperty $reflector,\n DocBlock $docBlockObj\n ): OutputType;\n\n /**\n * @param (InputType&GraphQLType)|null $subType\n *\n * @return InputType&GraphQLType\n */\n public function toGraphQLInputType(\n Type $type,\n InputType|null $subType,\n string $argumentName,\n ReflectionMethod|ReflectionProperty $reflector,\n DocBlock $docBlockObj\n ): InputType;\n")),(0,i.yg)("h3",{id:"improvements-1"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#510"),(0,i.yg)("li",{parentName:"ul"},"#508")),(0,i.yg)("h2",{id:"500"},"5.0.0"),(0,i.yg)("h3",{id:"dependencies"},"Dependencies"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.yg)("h2",{id:"430"},"4.3.0"),(0,i.yg)("h3",{id:"breaking-change"},"Breaking change"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The method ",(0,i.yg)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.yg)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.yg)("h3",{id:"minor-changes-1"},"Minor changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.yg)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h3",{id:"breaking-change-1"},"Breaking change"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h3",{id:"new-features-1"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/input-types#input-attribute"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h3",{id:"breaking-change-2"},"Breaking change"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h3",{id:"new-features-2"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h3",{id:"minor-changes-2"},"Minor changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h3",{id:"miscellaneous"},"Miscellaneous"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h3",{id:"new-features-3"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.yg)("p",null,"New framework specific features:"),(0,i.yg)("h3",{id:"symfony"},"Symfony"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h3",{id:"laravel"},"Laravel"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h3",{id:"internals"},"Internals"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6053],{90333:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>r,default:()=>g,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var t=a(58168),i=(a(96540),a(15680));a(67443);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"version-7.0.0/changelog",title:"Changelog",description:"7.0.0",source:"@site/versioned_docs/version-7.0.0/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/7.0.0/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/CHANGELOG.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/7.0.0/semver"}},p={},s=[{value:"7.0.0",id:"700",level:2},{value:"Breaking Changes",id:"breaking-changes",level:3},{value:"New Features",id:"new-features",level:3},{value:"Improvements",id:"improvements",level:3},{value:"Minor Changes",id:"minor-changes",level:3},{value:"6.2.3",id:"623",level:2},{value:"6.2.2",id:"622",level:2},{value:"6.2.1",id:"621",level:2},{value:"6.2.0",id:"620",level:2},{value:"6.1.0",id:"610",level:2},{value:"Breaking Changes",id:"breaking-changes-1",level:3},{value:"Improvements",id:"improvements-1",level:3},{value:"5.0.0",id:"500",level:2},{value:"Dependencies",id:"dependencies",level:3},{value:"4.3.0",id:"430",level:2},{value:"Breaking change",id:"breaking-change",level:3},{value:"Minor changes",id:"minor-changes-1",level:3},{value:"4.2.0",id:"420",level:2},{value:"Breaking change",id:"breaking-change-1",level:3},{value:"New features",id:"new-features-1",level:3},{value:"4.1.0",id:"410",level:2},{value:"Breaking change",id:"breaking-change-2",level:3},{value:"New features",id:"new-features-2",level:3},{value:"Minor changes",id:"minor-changes-2",level:3},{value:"Miscellaneous",id:"miscellaneous",level:3},{value:"4.0.0",id:"400",level:2},{value:"New features",id:"new-features-3",level:3},{value:"Symfony",id:"symfony",level:3},{value:"Laravel",id:"laravel",level:3},{value:"Internals",id:"internals",level:3}],d={toc:s},u="wrapper";function g(e){let{components:n,...a}=e;return(0,i.yg)(u,(0,t.A)({},d,a,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"700"},"7.0.0"),(0,i.yg)("h3",{id:"breaking-changes"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#664 Replaces ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/class-explorer"},"thecodingmachine/class-explorer")," with ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/alekitto/class-finder"},"kcs/class-finder")," resulting in the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setClassNameMapper")," being renamed to ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setFinder"),". This now expects an instance of ",(0,i.yg)("inlineCode",{parentName:"li"},"Kcs\\ClassFinder\\Finder")," instead of ",(0,i.yg)("inlineCode",{parentName:"li"},"Kcs\\ClassFinder\\Finder\\FinderInterface"),". @fogrye")),(0,i.yg)("h3",{id:"new-features"},"New Features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#649 Adds support for ",(0,i.yg)("inlineCode",{parentName:"li"},"subscription")," operations. @oojacoboo"),(0,i.yg)("li",{parentName:"ul"},"#612 Automatic query complexity analysis. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#611 Automatic persisted queries. @oprypkhantc")),(0,i.yg)("h3",{id:"improvements"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#658 Improves on prefetching for nested fields. @grynchuk"),(0,i.yg)("li",{parentName:"ul"},"#646 Improves exception handling during schema parsing. @fogrye"),(0,i.yg)("li",{parentName:"ul"},"#636 Allows the use of middleware on construtor params/fields. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#623 Improves support for description arguments on types/fields. @downace"),(0,i.yg)("li",{parentName:"ul"},"#628 Properly handles ",(0,i.yg)("inlineCode",{parentName:"li"},"@param")," annotations for generics support on field annotated constructor arguments. @oojacoboo"),(0,i.yg)("li",{parentName:"ul"},"#584 Immutability improvements across the codebase. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#588 Prefetch improvements. @oprpkhantc"),(0,i.yg)("li",{parentName:"ul"},"#606 Adds support for phpdoc descriptions and deprecation annotations on native enums. @mdoelker"),(0,i.yg)("li",{parentName:"ul"},"Thanks to @shish, @cvergne and @mshapovalov for updating the docs!")),(0,i.yg)("h3",{id:"minor-changes"},"Minor Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#639 Added support for Symfony 7. @janatjak")),(0,i.yg)("h2",{id:"623"},"6.2.3"),(0,i.yg)("p",null,"Adds support for ",(0,i.yg)("inlineCode",{parentName:"p"},"Psr\\Container")," 1.1 with #601"),(0,i.yg)("h2",{id:"622"},"6.2.2"),(0,i.yg)("p",null,"This is a very simple release. We support Doctrine annotation 1.x and we've deprecated ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory::setDoctrineAnnotationReader")," in favor of native PHP attributes."),(0,i.yg)("h2",{id:"621"},"6.2.1"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Added support for new ",(0,i.yg)("inlineCode",{parentName:"li"},"Void")," return types, allowing use of ",(0,i.yg)("inlineCode",{parentName:"li"},"void")," from operation resolvers. #574"),(0,i.yg)("li",{parentName:"ul"},"Improvements with authorization middleware #571"),(0,i.yg)("li",{parentName:"ul"},"Updated vendor dependencies: #580 #558")),(0,i.yg)("h2",{id:"620"},"6.2.0"),(0,i.yg)("p",null,"Lots of little nuggets in this release! We're now targeting PHP ^8.1 and have testing on 8.2."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Better support for union types and enums: #530, #535, #561, #570"),(0,i.yg)("li",{parentName:"ul"},"Various bug and interface fixes: #532, #575, #564"),(0,i.yg)("li",{parentName:"ul"},"GraphQL v15 required: #542"),(0,i.yg)("li",{parentName:"ul"},"Lots of codebase improvements, more strict typing: #548")),(0,i.yg)("p",null,"A special thanks to @rusted-love and @oprypkhantc for their contributions."),(0,i.yg)("h2",{id:"610"},"6.1.0"),(0,i.yg)("p",null,"A shoutout to @bladl for his work on this release, improving the code for better typing and PHP 8.0 syntax updates!"),(0,i.yg)("h3",{id:"breaking-changes-1"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#518 PSR-11 support now requires version 2"),(0,i.yg)("li",{parentName:"ul"},"#508 Due to some of the code improvements, additional typing has been added to some interfaces/classes. For instance, ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface::toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface::toGraphQLInputType")," now have the following signatures:")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"}," /**\n * @param (OutputType&GraphQLType)|null $subType\n *\n * @return OutputType&GraphQLType\n */\n public function toGraphQLOutputType(\n Type $type,\n OutputType|null $subType,\n ReflectionMethod|ReflectionProperty $reflector,\n DocBlock $docBlockObj\n ): OutputType;\n\n /**\n * @param (InputType&GraphQLType)|null $subType\n *\n * @return InputType&GraphQLType\n */\n public function toGraphQLInputType(\n Type $type,\n InputType|null $subType,\n string $argumentName,\n ReflectionMethod|ReflectionProperty $reflector,\n DocBlock $docBlockObj\n ): InputType;\n")),(0,i.yg)("h3",{id:"improvements-1"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#510"),(0,i.yg)("li",{parentName:"ul"},"#508")),(0,i.yg)("h2",{id:"500"},"5.0.0"),(0,i.yg)("h3",{id:"dependencies"},"Dependencies"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.yg)("h2",{id:"430"},"4.3.0"),(0,i.yg)("h3",{id:"breaking-change"},"Breaking change"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The method ",(0,i.yg)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.yg)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.yg)("h3",{id:"minor-changes-1"},"Minor changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.yg)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h3",{id:"breaking-change-1"},"Breaking change"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h3",{id:"new-features-1"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/input-types#input-attribute"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h3",{id:"breaking-change-2"},"Breaking change"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h3",{id:"new-features-2"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h3",{id:"minor-changes-2"},"Minor changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h3",{id:"miscellaneous"},"Miscellaneous"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h3",{id:"new-features-3"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.yg)("p",null,"New framework specific features:"),(0,i.yg)("h3",{id:"symfony"},"Symfony"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h3",{id:"laravel"},"Laravel"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h3",{id:"internals"},"Internals"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/18100524.82b29572.js b/assets/js/18100524.0c790315.js similarity index 99% rename from assets/js/18100524.82b29572.js rename to assets/js/18100524.0c790315.js index e239ba9f9..aa4dd52f7 100644 --- a/assets/js/18100524.82b29572.js +++ b/assets/js/18100524.0c790315.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1264],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),u=a(57485),s=a(31682),i=a(89466);function y(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??y(a);return function(e){const t=(0,s.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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(!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}),[y,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=u??y;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:u,tabValues:s}=e;const i=[],{blockElementScrollPositionUntilNextRender:y}=(0,o.a_)(),c=e=>{const t=e.currentTarget,a=i.indexOf(t),n=s[a].value;n!==l&&(y(t),u(n))},d=e=>{let t=null;switch(e.key){case"Enter":c(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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:c},o,{className:(0,p.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},58164:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>y});var n=a(58168),r=(a(96540),a(15680)),p=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"}},i={},y=[{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}],c={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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([[1264],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),u=a(57485),s=a(31682),i=a(89466);function y(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??y(a);return function(e){const t=(0,s.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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(!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}),[y,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=u??y;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:u,tabValues:s}=e;const i=[],{blockElementScrollPositionUntilNextRender:y}=(0,o.a_)(),c=e=>{const t=e.currentTarget,a=i.indexOf(t),n=s[a].value;n!==l&&(y(t),u(n))},d=e=>{let t=null;switch(e.key){case"Enter":c(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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:c},o,{className:(0,p.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},58164:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>y});var n=a(58168),r=(a(96540),a(15680)),p=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"}},i={},y=[{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}],c={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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.20ea55e4.js b/assets/js/1891fd2b.a8e3c91b.js similarity index 99% rename from assets/js/1891fd2b.20ea55e4.js rename to assets/js/1891fd2b.a8e3c91b.js index 14843eedc..f57032059 100644 --- a/assets/js/1891fd2b.20ea55e4.js +++ b/assets/js/1891fd2b.a8e3c91b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3460],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),i=a(89466);function y(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??y(a);return function(e){const t=(0,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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(!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}),[y,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=s??y;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:y}=(0,o.a_)(),c=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(y(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":c(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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:c},o,{className:(0,p.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},14716:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>y});var n=a(58168),r=(a(96540),a(15680)),p=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],c={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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([[3460],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),i=a(89466);function y(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??y(a);return function(e){const t=(0,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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(!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}),[y,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=s??y;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:y}=(0,o.a_)(),c=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(y(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":c(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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:c},o,{className:(0,p.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},14716:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>y});var n=a(58168),r=(a(96540),a(15680)),p=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],c={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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.6704a06c.js b/assets/js/18d6c9c9.e70b6848.js similarity index 99% rename from assets/js/18d6c9c9.6704a06c.js rename to assets/js/18d6c9c9.e70b6848.js index 71c7d10b3..84ba63753 100644 --- a/assets/js/18d6c9c9.6704a06c.js +++ b/assets/js/18d6c9c9.e70b6848.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4422],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var r=n(96540),a=n(20053);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.A)(s.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>T});var r=n(58168),a=n(96540),s=n(20053),o=n(23104),l=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:n,selectedValue:l,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return a.createElement("li",(0,r.A)({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.A)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(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 w(e){const t=f(e);return a.createElement("div",{className:(0,s.A)("tabs-container",g.tabList)},a.createElement(y,(0,r.A)({},e,t)),a.createElement(v,(0,r.A)({},e,t)))}function T(e){const t=(0,b.A)();return a.createElement(w,(0,r.A)({key:String(t)},e))}},61770:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>i,contentTitle:()=>o,default:()=>h,frontMatter:()=>s,metadata:()=>l,toc:()=>u});var r=n(58168),a=(n(96540),n(15680));n(67443),n(11470),n(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"docs",previous:{title:"Query plan",permalink:"/docs/6.1/query-plan"},next:{title:"File uploads",permalink:"/docs/6.1/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.yg)(d,(0,r.A)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("h2",{id:"the-problem"},"The problem"),(0,a.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,a.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,a.yg)("p",null,"A naive implementation will do this:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,a.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,a.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/6.1/query-plan"},'"analyzing the query plan" documentation'),"."),(0,a.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,a.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,a.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,a.yg)("p",null,"For instance:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("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([[4422],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var r=n(96540),a=n(20053);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.A)(s.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>T});var r=n(58168),a=n(96540),s=n(20053),o=n(23104),l=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:n,selectedValue:l,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return a.createElement("li",(0,r.A)({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.A)("tabs__item",g.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(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 w(e){const t=f(e);return a.createElement("div",{className:(0,s.A)("tabs-container",g.tabList)},a.createElement(y,(0,r.A)({},e,t)),a.createElement(v,(0,r.A)({},e,t)))}function T(e){const t=(0,b.A)();return a.createElement(w,(0,r.A)({key:String(t)},e))}},61770:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>i,contentTitle:()=>o,default:()=>h,frontMatter:()=>s,metadata:()=>l,toc:()=>u});var r=n(58168),a=(n(96540),n(15680));n(67443),n(11470),n(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"docs",previous:{title:"Query plan",permalink:"/docs/6.1/query-plan"},next:{title:"File uploads",permalink:"/docs/6.1/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.yg)(d,(0,r.A)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("h2",{id:"the-problem"},"The problem"),(0,a.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,a.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,a.yg)("p",null,"A naive implementation will do this:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,a.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,a.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/6.1/query-plan"},'"analyzing the query plan" documentation'),"."),(0,a.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,a.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,a.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,a.yg)("p",null,"For instance:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("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/1aa05129.6d8f74c5.js b/assets/js/1aa05129.c022cfc4.js similarity index 98% rename from assets/js/1aa05129.6d8f74c5.js rename to assets/js/1aa05129.c022cfc4.js index 697b4d1e2..7f562a12d 100644 --- a/assets/js/1aa05129.6d8f74c5.js +++ b/assets/js/1aa05129.c022cfc4.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2207],{13970:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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([[2207],{13970:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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/1af245cd.de613831.js b/assets/js/1af245cd.1a292e94.js similarity index 99% rename from assets/js/1af245cd.de613831.js rename to assets/js/1af245cd.1a292e94.js index 3634e30da..9bd6159df 100644 --- a/assets/js/1af245cd.de613831.js +++ b/assets/js/1af245cd.1a292e94.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2965],{19365:(t,e,n)=>{n.d(e,{A:()=>i});var a=n(96540),r=n(20053);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.A)(o.tabItem,i),hidden:n},e)}},11470:(t,e,n)=>{n.d(e,{A:()=>w});var a=n(58168),r=n(96540),o=n(20053),i=n(23104),s=n(56347),l=n(57485),u=n(31682),c=n(89466);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.X)(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 g(t){let{queryString:e=!1,groupId:n}=t;const a=(0,s.W6)(),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.aZ)(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,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]=g({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.Dv)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),m=(()=>{const t=l??p;return h({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{m&&s(m)}),[m]);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),b(t)}),[u,b,o]),tabValues:o}}var m=n(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(t){let{className:e,block:n,selectedValue:s,selectValue:l,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),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.A)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.A)({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.A)("tabs__item",y.tabItem,i?.className,{"tabs__item--active":s===e})}),n??e)})))}function A(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=b(t);return r.createElement("div",{className:(0,o.A)("tabs-container",y.tabList)},r.createElement(f,(0,a.A)({},t,e)),r.createElement(A,(0,a.A)({},t,e)))}function w(t){const e=(0,m.A)();return r.createElement(v,(0,a.A)({key:String(e)},t))}},62002:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>l,default:()=>g,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),o=(n(67443),n(11470)),i=n(19365);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-7.0.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-7.0.0/doctrine-annotations-attributes.mdx",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/7.0.0/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/doctrine-annotations-attributes.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"docs",previous:{title:"Migrating",permalink:"/docs/7.0.0/migrating"},next:{title:"Annotations reference",permalink:"/docs/7.0.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 g(t){let{components:e,...n}=t;return(0,r.yg)(h,(0,a.A)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"Please note that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("strong",null,"Heads up!"),(0,r.yg)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",null,"PhpStorm via the ",(0,r.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.yg)("li",null,"Eclipse via the ",(0,r.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.yg)("li",null,"Netbeans has native support")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.yg)("p",null,"The same code can be written this way:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.yg)("p",null,"They support the same attributes too."),(0,r.yg)("p",null,"A few notable differences:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.yg)("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.yg)("p",null,"Let's take an example with the ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/autowiring"},(0,r.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))),(0,r.yg)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,r.yg)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2965],{19365:(t,e,n)=>{n.d(e,{A:()=>i});var a=n(96540),r=n(20053);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.A)(o.tabItem,i),hidden:n},e)}},11470:(t,e,n)=>{n.d(e,{A:()=>w});var a=n(58168),r=n(96540),o=n(20053),i=n(23104),s=n(56347),l=n(57485),u=n(31682),c=n(89466);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.X)(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 g(t){let{queryString:e=!1,groupId:n}=t;const a=(0,s.W6)(),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.aZ)(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,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]=g({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.Dv)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),m=(()=>{const t=l??p;return h({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{m&&s(m)}),[m]);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),b(t)}),[u,b,o]),tabValues:o}}var m=n(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(t){let{className:e,block:n,selectedValue:s,selectValue:l,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),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.A)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.A)({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.A)("tabs__item",y.tabItem,i?.className,{"tabs__item--active":s===e})}),n??e)})))}function A(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=b(t);return r.createElement("div",{className:(0,o.A)("tabs-container",y.tabList)},r.createElement(f,(0,a.A)({},t,e)),r.createElement(A,(0,a.A)({},t,e)))}function w(t){const e=(0,m.A)();return r.createElement(v,(0,a.A)({key:String(e)},t))}},62002:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>l,default:()=>g,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),o=(n(67443),n(11470)),i=n(19365);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-7.0.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-7.0.0/doctrine-annotations-attributes.mdx",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/7.0.0/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/doctrine-annotations-attributes.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"docs",previous:{title:"Migrating",permalink:"/docs/7.0.0/migrating"},next:{title:"Annotations reference",permalink:"/docs/7.0.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 g(t){let{components:e,...n}=t;return(0,r.yg)(h,(0,a.A)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"Please note that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("strong",null,"Heads up!"),(0,r.yg)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",null,"PhpStorm via the ",(0,r.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.yg)("li",null,"Eclipse via the ",(0,r.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.yg)("li",null,"Netbeans has native support")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.yg)("p",null,"The same code can be written this way:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.yg)("p",null,"They support the same attributes too."),(0,r.yg)("p",null,"A few notable differences:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.yg)("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.yg)("p",null,"Let's take an example with the ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/autowiring"},(0,r.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))),(0,r.yg)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,r.yg)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1b1927f4.f6cb8ea8.js b/assets/js/1b1927f4.d6cee834.js similarity index 98% rename from assets/js/1b1927f4.f6cb8ea8.js rename to assets/js/1b1927f4.d6cee834.js index c76303a87..0f312e240 100644 --- a/assets/js/1b1927f4.f6cb8ea8.js +++ b/assets/js/1b1927f4.d6cee834.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5099],{9717:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>p,default:()=>y,frontMatter:()=>l,metadata:()=>o,toc:()=>u});var a=n(58168),i=(n(96540),n(15680));n(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.1/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/6.1/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 y(e){let{components:t,...n}=e;return(0,i.yg)(r,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.yg)("h2",{id:"example"},"Example"),(0,i.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,i.yg)("a",{parentName:"p",href:"/docs/6.1/external-type-declaration"},'"external" type')," mapping the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.yg)("p",null,"First of all, we specify ",(0,i.yg)("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.yg)("p",null,"Then, we specify ",(0,i.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,i.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,i.yg)("p",null,"Finally, we can write our requests:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,i.yg)("p",null,"Is a result, when the end user calls the ",(0,i.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,i.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,i.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,i.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,i.yg)("p",null,"If you want to extend a type using the ",(0,i.yg)("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.yg)("p",null,"So instead of writing:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,i.yg)("p",null,"you will write:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n')),(0,i.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5099],{9717:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>p,default:()=>y,frontMatter:()=>l,metadata:()=>o,toc:()=>u});var a=n(58168),i=(n(96540),n(15680));n(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.1/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/6.1/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 y(e){let{components:t,...n}=e;return(0,i.yg)(r,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.yg)("h2",{id:"example"},"Example"),(0,i.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,i.yg)("a",{parentName:"p",href:"/docs/6.1/external-type-declaration"},'"external" type')," mapping the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.yg)("p",null,"First of all, we specify ",(0,i.yg)("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.yg)("p",null,"Then, we specify ",(0,i.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,i.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,i.yg)("p",null,"Finally, we can write our requests:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,i.yg)("p",null,"Is a result, when the end user calls the ",(0,i.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,i.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,i.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,i.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,i.yg)("p",null,"If you want to extend a type using the ",(0,i.yg)("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.yg)("p",null,"So instead of writing:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,i.yg)("p",null,"you will write:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n')),(0,i.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1ba75d10.53c389e0.js b/assets/js/1ba75d10.d93ecfdd.js similarity index 99% rename from assets/js/1ba75d10.53c389e0.js rename to assets/js/1ba75d10.d93ecfdd.js index cd8b2a877..8bdf6bb43 100644 --- a/assets/js/1ba75d10.53c389e0.js +++ b/assets/js/1ba75d10.d93ecfdd.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8470],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(o.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>A});var n=a(58168),r=a(96540),o=a(20053),u=a(23104),l=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(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 T(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},r.createElement(g,(0,n.A)({},e,t)),r.createElement(y,(0,n.A)({},e,t)))}function A(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},61366:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),o=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(m,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, mutations are created ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/queries"},"like queries"),"."),(0,r.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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([[8470],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(o.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>A});var n=a(58168),r=a(96540),o=a(20053),u=a(23104),l=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(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 T(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},r.createElement(g,(0,n.A)({},e,t)),r.createElement(y,(0,n.A)({},e,t)))}function A(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},61366:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),o=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(m,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, mutations are created ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/queries"},"like queries"),"."),(0,r.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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/1ca907c0.c014be77.js b/assets/js/1ca907c0.0d0f4c41.js similarity index 98% rename from assets/js/1ca907c0.c014be77.js rename to assets/js/1ca907c0.0d0f4c41.js index cbcd233d2..86acf2f60 100644 --- a/assets/js/1ca907c0.c014be77.js +++ b/assets/js/1ca907c0.0d0f4c41.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1431],{85483:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),r=(i(96540),i(15680));i(67443);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-7.0.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-7.0.0/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/7.0.0/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/implementing-security.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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/7.0.0/fine-grained-security"},next:{title:"Operation complexity",permalink:"/docs/7.0.0/operation-complexity"}},c={},l=[],u={toc:l},p="wrapper";function h(e){let{components:t,...i}=e;return(0,r.yg)(p,(0,n.A)({},u,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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([[1431],{85483:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),r=(i(96540),i(15680));i(67443);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-7.0.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-7.0.0/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/7.0.0/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/implementing-security.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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/7.0.0/fine-grained-security"},next:{title:"Operation complexity",permalink:"/docs/7.0.0/operation-complexity"}},c={},l=[],u={toc:l},p="wrapper";function h(e){let{components:t,...i}=e;return(0,r.yg)(p,(0,n.A)({},u,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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/1d20a4b3.7d27119c.js b/assets/js/1d20a4b3.4bdc2a57.js similarity index 99% rename from assets/js/1d20a4b3.7d27119c.js rename to assets/js/1d20a4b3.4bdc2a57.js index 16e24bcbb..efe244334 100644 --- a/assets/js/1d20a4b3.7d27119c.js +++ b/assets/js/1d20a4b3.4bdc2a57.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2596],{19365:(e,a,t)=>{t.d(a,{A:()=>l});var n=t(96540),r=t(20053);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:a,hidden:t,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(o.tabItem,l),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),o=t(20053),l=t(23104),i=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function g(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function d(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,i.W6)(),o=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(o),(0,r.useCallback)((e=>{if(!o)return;const a=new URLSearchParams(n.location.search);a.set(o,e),n.replace({...n.location,search:a.toString()})}),[o,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,o=g(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!d({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:o}))),[s,u]=y({queryString:t,groupId:n}),[c,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,o]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:a,block:t,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.a_)(),g=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==i&&(c(a),s(n))},d=e=>{let a=null;switch(e.key){case"Enter":g(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:l}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:i===a?0:-1,"aria-selected":i===a,key:a,ref:e=>p.push(e),onKeyDown:d,onClick:g},l,{className:(0,o.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":i===a})}),t??a)})))}function v(e){let{lazy:a,children:t,selectedValue:n}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function N(e){const a=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,a)),r.createElement(v,(0,n.A)({},e,a)))}function T(e){const a=(0,m.A)();return r.createElement(N,(0,n.A)({key:String(a)},e))}},53945:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),o=(t(67443),t(11470)),l=t(19365);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-7.0.0/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-7.0.0/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/7.0.0/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/fine-grained-security.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},sidebar:"docs",previous:{title:"Authentication and authorization",permalink:"/docs/7.0.0/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/7.0.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}],g={toc:c},d="wrapper";function y(e){let{components:a,...t}=e;return(0,r.yg)(d,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"If the ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/authentication-authorization#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.yg)("li",{parentName:"ul"},"...")),(0,r.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.yg)("code",null,"@Security")," annotation and Symfony's ",(0,r.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.yg)("h2",{id:"the-is_granted-function"},"The ",(0,r.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.yg)("p",null,"is similar to"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.yg)("p",null,"In addition, the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/authentication-authorization#not-throwing-errors"},(0,r.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"You cannot use the ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.yg)("p",null,"If you are using Laravel, you will ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.yg)("p",null,"If you are using another framework, you need to know that the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.yg)("inlineCode",{parentName:"p"},"AuthorizationService"),". See ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2596],{19365:(e,a,t)=>{t.d(a,{A:()=>l});var n=t(96540),r=t(20053);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:a,hidden:t,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(o.tabItem,l),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),o=t(20053),l=t(23104),i=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function g(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function d(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,i.W6)(),o=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(o),(0,r.useCallback)((e=>{if(!o)return;const a=new URLSearchParams(n.location.search);a.set(o,e),n.replace({...n.location,search:a.toString()})}),[o,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,o=g(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!d({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:o}))),[s,u]=y({queryString:t,groupId:n}),[c,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,o]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:a,block:t,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.a_)(),g=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==i&&(c(a),s(n))},d=e=>{let a=null;switch(e.key){case"Enter":g(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:l}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:i===a?0:-1,"aria-selected":i===a,key:a,ref:e=>p.push(e),onKeyDown:d,onClick:g},l,{className:(0,o.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":i===a})}),t??a)})))}function v(e){let{lazy:a,children:t,selectedValue:n}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function N(e){const a=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,a)),r.createElement(v,(0,n.A)({},e,a)))}function T(e){const a=(0,m.A)();return r.createElement(N,(0,n.A)({key:String(a)},e))}},53945:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),o=(t(67443),t(11470)),l=t(19365);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-7.0.0/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-7.0.0/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/7.0.0/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/fine-grained-security.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},sidebar:"docs",previous:{title:"Authentication and authorization",permalink:"/docs/7.0.0/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/7.0.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}],g={toc:c},d="wrapper";function y(e){let{components:a,...t}=e;return(0,r.yg)(d,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"If the ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/authentication-authorization#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.yg)("li",{parentName:"ul"},"...")),(0,r.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.yg)("code",null,"@Security")," annotation and Symfony's ",(0,r.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.yg)("h2",{id:"the-is_granted-function"},"The ",(0,r.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.yg)("p",null,"is similar to"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.yg)("p",null,"In addition, the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/authentication-authorization#not-throwing-errors"},(0,r.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"You cannot use the ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.yg)("p",null,"If you are using Laravel, you will ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.yg)("p",null,"If you are using another framework, you need to know that the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.yg)("inlineCode",{parentName:"p"},"AuthorizationService"),". See ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1d703573.702ab7f9.js b/assets/js/1d703573.eba89edd.js similarity index 97% rename from assets/js/1d703573.702ab7f9.js rename to assets/js/1d703573.eba89edd.js index 8a8aac952..ec18d56da 100644 --- a/assets/js/1d703573.702ab7f9.js +++ b/assets/js/1d703573.eba89edd.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4671],{62190:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:l},g="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,r.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4671],{62190:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:l},g="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,r.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1e2c5f46.45e28f07.js b/assets/js/1e2c5f46.65b9961d.js similarity index 98% rename from assets/js/1e2c5f46.45e28f07.js rename to assets/js/1e2c5f46.65b9961d.js index fb128afd4..0d4eab3f0 100644 --- a/assets/js/1e2c5f46.45e28f07.js +++ b/assets/js/1e2c5f46.65b9961d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2491],{30241:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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/6.1/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/semver.md",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Annotations reference",permalink:"/docs/6.1/annotations-reference"},next:{title:"Changelog",permalink:"/docs/6.1/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^6"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~6.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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([[2491],{30241:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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/6.1/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/semver.md",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Annotations reference",permalink:"/docs/6.1/annotations-reference"},next:{title:"Changelog",permalink:"/docs/6.1/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^6"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~6.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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.de27ac75.js b/assets/js/1e6ec01e.ac95ff0a.js similarity index 99% rename from assets/js/1e6ec01e.de27ac75.js rename to assets/js/1e6ec01e.ac95ff0a.js index de7a78145..0cd57cc86 100644 --- a/assets/js/1e6ec01e.de27ac75.js +++ b/assets/js/1e6ec01e.ac95ff0a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4761],{89714:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=t(58168),r=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function u(e){let{components:a,...t}=e;return(0,r.yg)(h,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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([[4761],{89714:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var n=t(58168),r=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function u(e){let{components:a,...t}=e;return(0,r.yg)(h,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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/1e7fe27e.a69acb67.js b/assets/js/1e7fe27e.46ea8ff8.js similarity index 99% rename from assets/js/1e7fe27e.a69acb67.js rename to assets/js/1e7fe27e.46ea8ff8.js index b89c0c2da..65a65283a 100644 --- a/assets/js/1e7fe27e.a69acb67.js +++ b/assets/js/1e7fe27e.46ea8ff8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[79],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),g(e)}),[u,g,i]),tabValues:i}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function T(e){const t=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},71930:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),i=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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,...a}=e;return(0,r.yg)(h,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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([[79],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),g(e)}),[u,g,i]),tabValues:i}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function T(e){const t=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},71930:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),i=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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,...a}=e;return(0,r.yg)(h,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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.734e5d0e.js b/assets/js/1ea13486.63f904ea.js similarity index 98% rename from assets/js/1ea13486.734e5d0e.js rename to assets/js/1ea13486.63f904ea.js index 817e4069b..7e9ba72a1 100644 --- a/assets/js/1ea13486.734e5d0e.js +++ b/assets/js/1ea13486.63f904ea.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2112],{52660:(e,t,r)=>{r.r(t),r.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>h,frontMatter:()=>n,metadata:()=>u,toc:()=>d});var i=r(58168),s=(r(96540),r(15680)),a=r(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(c,(0,i.A)({},p,r,{components:t,mdxType:"MDXLayout"}),(0,s.yg)("h2",{id:"the-problem"},"The problem"),(0,s.yg)("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.yg)("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.yg)("h2",{id:"apollo-apq"},"Apollo APQ"),(0,s.yg)("p",null,(0,s.yg)("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.yg)("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.yg)(a.K,{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.yg)("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.yg)("p",null,"Because query identifiers are deterministic hashes, clients can generate them at runtime. No additional build steps are required."),(0,s.yg)("h2",{id:"setup"},"Setup"),(0,s.yg)("p",null,"To use Automatic persisted queries with GraphQLite, you may use\n",(0,s.yg)("inlineCode",{parentName:"p"},"useAutomaticPersistedQueries")," method when building your PSR-15 middleware:"),(0,s.yg)("pre",null,(0,s.yg)("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([[2112],{52660:(e,t,r)=>{r.r(t),r.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>h,frontMatter:()=>n,metadata:()=>u,toc:()=>d});var i=r(58168),s=(r(96540),r(15680)),a=r(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(c,(0,i.A)({},p,r,{components:t,mdxType:"MDXLayout"}),(0,s.yg)("h2",{id:"the-problem"},"The problem"),(0,s.yg)("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.yg)("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.yg)("h2",{id:"apollo-apq"},"Apollo APQ"),(0,s.yg)("p",null,(0,s.yg)("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.yg)("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.yg)(a.K,{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.yg)("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.yg)("p",null,"Because query identifiers are deterministic hashes, clients can generate them at runtime. No additional build steps are required."),(0,s.yg)("h2",{id:"setup"},"Setup"),(0,s.yg)("p",null,"To use Automatic persisted queries with GraphQLite, you may use\n",(0,s.yg)("inlineCode",{parentName:"p"},"useAutomaticPersistedQueries")," method when building your PSR-15 middleware:"),(0,s.yg)("pre",null,(0,s.yg)("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.94425734.js b/assets/js/1edb88e5.0bec25f2.js similarity index 99% rename from assets/js/1edb88e5.94425734.js rename to assets/js/1edb88e5.0bec25f2.js index 97e7c8511..1faafcb3f 100644 --- a/assets/js/1edb88e5.94425734.js +++ b/assets/js/1edb88e5.0bec25f2.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1245],{19365:(e,t,n)=>{n.d(t,{A:()=>l});var a=n(96540),r=n(20053);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.A)(i.tabItem,l),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>N});var a=n(58168),r=n(96540),i=n(20053),l=n(23104),o=n(56347),u=n(57485),s=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 m(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(!y({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}),[d,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return y({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),m(e)}),[s,m,i]),tabValues:i}}var f=n(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,l.a_)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(d(t),u(a))},y=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.A)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:y,onClick:p},l,{className:(0,i.A)("tabs__item",g.tabItem,l?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(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 w(e){const t=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",g.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function N(e){const t=(0,f.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},711:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>l,default:()=>p,frontMatter:()=>i,metadata:()=>o,toc:()=>s});var a=n(58168),r=(n(96540),n(15680));n(67443),n(11470),n(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.1/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/6.1/multiple-output-types"}},u={},s=[],c={toc:s},d="wrapper";function p(e){let{components:t,...n}=e;return(0,r.yg)(d,(0,a.A)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.1/extend-type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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([[1245],{19365:(e,t,n)=>{n.d(t,{A:()=>l});var a=n(96540),r=n(20053);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.A)(i.tabItem,l),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>N});var a=n(58168),r=n(96540),i=n(20053),l=n(23104),o=n(56347),u=n(57485),s=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 m(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(!y({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}),[d,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),f=(()=>{const e=u??d;return y({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),m(e)}),[s,m,i]),tabValues:i}}var f=n(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,l.a_)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(d(t),u(a))},y=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.A)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:y,onClick:p},l,{className:(0,i.A)("tabs__item",g.tabItem,l?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(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 w(e){const t=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",g.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function N(e){const t=(0,f.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},711:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>l,default:()=>p,frontMatter:()=>i,metadata:()=>o,toc:()=>s});var a=n(58168),r=(n(96540),n(15680));n(67443),n(11470),n(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.1/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/6.1/multiple-output-types"}},u={},s=[],c={toc:s},d="wrapper";function p(e){let{components:t,...n}=e;return(0,r.yg)(d,(0,a.A)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.1/extend-type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.48924c16.js b/assets/js/1f5af0f2.7701c5a6.js similarity index 98% rename from assets/js/1f5af0f2.48924c16.js rename to assets/js/1f5af0f2.7701c5a6.js index 51f42be7c..499b4cdf3 100644 --- a/assets/js/1f5af0f2.48924c16.js +++ b/assets/js/1f5af0f2.7701c5a6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2962],{40611:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>d,frontMatter:()=>s,metadata:()=>i,toc:()=>l});var n=a(58168),p=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:t,...a}=e;return(0,p.yg)(y,(0,n.A)({},r,a,{components:t,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.yg)("p",null,"GraphQL comes with an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID!")\n */\n')),(0,p.yg)("h2",{id:"usage"},"Usage"),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.yg)("p",null,"You can use the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Query")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Field")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@SourceField"))),(0,p.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.yg)("p",null,"In order to create a custom output type, you need to:"),(0,p.yg)("ol",null,(0,p.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,p.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.yg)("p",null,"You'll find more details on the ",(0,p.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,p.yg)("hr",null),(0,p.yg)("p",null,"In order to find existing types, the schema is using ",(0,p.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,p.yg)("p",null,"Any class extending ",(0,p.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.yg)("p",null,"The easiest way is to use a ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.yg)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2962],{40611:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>d,frontMatter:()=>s,metadata:()=>i,toc:()=>l});var n=a(58168),p=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:t,...a}=e;return(0,p.yg)(y,(0,n.A)({},r,a,{components:t,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.yg)("p",null,"GraphQL comes with an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID!")\n */\n')),(0,p.yg)("h2",{id:"usage"},"Usage"),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.yg)("p",null,"You can use the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Query")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Field")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@SourceField"))),(0,p.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.yg)("p",null,"In order to create a custom output type, you need to:"),(0,p.yg)("ol",null,(0,p.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,p.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.yg)("p",null,"You'll find more details on the ",(0,p.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,p.yg)("hr",null),(0,p.yg)("p",null,"In order to find existing types, the schema is using ",(0,p.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,p.yg)("p",null,"Any class extending ",(0,p.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.yg)("p",null,"The easiest way is to use a ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.yg)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1f5e9707.a495c84c.js b/assets/js/1f5e9707.687e3b9b.js similarity index 99% rename from assets/js/1f5e9707.a495c84c.js rename to assets/js/1f5e9707.687e3b9b.js index 8f84ac208..adab6c423 100644 --- a/assets/js/1f5e9707.a495c84c.js +++ b/assets/js/1f5e9707.687e3b9b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7591],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var r=a(96540),t=a(20053);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,t.A)(o.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>$});var r=a(58168),t=a(96540),o=a(20053),i=a(23104),l=a(56347),s=a(57485),c=a(31682),p=a(89466);function u(e){return function(e){return t.Children.map(e,(e=>{if(!e||(0,t.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:a,attributes:r,default:t}}=e;return{value:n,label:a,attributes:r,default:t}}))}function d(e){const{values:n,children:a}=e;return(0,t.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function h(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:a}=e;const r=(0,l.W6)(),o=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(o),(0,t.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 y(e){const{defaultValue:n,queryString:a=!1,groupId:r}=e,o=d(e),[i,l]=(0,t.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,c]=m({queryString:a,groupId:r}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,p.Dv)(a);return[r,(0,t.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:r}),g=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,t.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:i,selectValue:(0,t.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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),d=e=>{const n=e.currentTarget,a=p.indexOf(n),r=c[a].value;r!==l&&(u(n),s(r))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;n=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;n=p[a]??p[p.length-1];break}}n?.focus()};return t.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return t.createElement("li",(0,r.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":l===n})}),a??n)})))}function w(e){let{lazy:n,children:a,selectedValue:r}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,t.cloneElement)(e,{className:"margin-top--md"}):null}return t.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,t.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=y(e);return t.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},t.createElement(b,(0,r.A)({},e,n)),t.createElement(w,(0,r.A)({},e,n)))}function $(e){const n=(0,g.A)();return t.createElement(v,(0,r.A)({key:String(n)},e))}},32140:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var r=a(58168),t=(a(96540),a(15680)),o=(a(67443),a(11470)),i=a(19365);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-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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},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:n,...a}=e;return(0,t.yg)(h,(0,r.A)({},d,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,t.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("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([[7591],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var r=a(96540),t=a(20053);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,t.A)(o.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>$});var r=a(58168),t=a(96540),o=a(20053),i=a(23104),l=a(56347),s=a(57485),c=a(31682),p=a(89466);function u(e){return function(e){return t.Children.map(e,(e=>{if(!e||(0,t.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:a,attributes:r,default:t}}=e;return{value:n,label:a,attributes:r,default:t}}))}function d(e){const{values:n,children:a}=e;return(0,t.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function h(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:a}=e;const r=(0,l.W6)(),o=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(o),(0,t.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 y(e){const{defaultValue:n,queryString:a=!1,groupId:r}=e,o=d(e),[i,l]=(0,t.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,c]=m({queryString:a,groupId:r}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,p.Dv)(a);return[r,(0,t.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:r}),g=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,t.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:i,selectValue:(0,t.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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),d=e=>{const n=e.currentTarget,a=p.indexOf(n),r=c[a].value;r!==l&&(u(n),s(r))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;n=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;n=p[a]??p[p.length-1];break}}n?.focus()};return t.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return t.createElement("li",(0,r.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":l===n})}),a??n)})))}function w(e){let{lazy:n,children:a,selectedValue:r}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,t.cloneElement)(e,{className:"margin-top--md"}):null}return t.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,t.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=y(e);return t.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},t.createElement(b,(0,r.A)({},e,n)),t.createElement(w,(0,r.A)({},e,n)))}function $(e){const n=(0,g.A)();return t.createElement(v,(0,r.A)({key:String(n)},e))}},32140:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var r=a(58168),t=(a(96540),a(15680)),o=(a(67443),a(11470)),i=a(19365);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-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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},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:n,...a}=e;return(0,t.yg)(h,(0,r.A)({},d,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,t.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("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.9d786417.js b/assets/js/2014e4e3.18ddacc7.js similarity index 98% rename from assets/js/2014e4e3.9d786417.js rename to assets/js/2014e4e3.18ddacc7.js index 10149bae3..55630cf1a 100644 --- a/assets/js/2014e4e3.9d786417.js +++ b/assets/js/2014e4e3.18ddacc7.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6481],{18650:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>l,default:()=>s,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},l=void 0,o={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},d=[],u={toc:d},y="wrapper";function s(e){let{components:t,...n}=e;return(0,i.yg)(y,(0,a.A)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,i.yg)("code",null,"#[Factory]")," tag, ",(0,i.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,i.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,i.yg)("p",null,"Just like with output type (that can be ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/extend-type"},"extended using the ",(0,i.yg)("inlineCode",{parentName:"a"},"ExtendType")," attribute"),"), you can extend/modify\nan input type using the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Decorate]")," attribute."),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Decorate]")," attribute to add additional fields to an input type that is already declared by a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Factory]")," attribute,\nor to modify the returned object."),(0,i.yg)("div",{class:"alert alert--info"},"The ",(0,i.yg)("code",null,"#[Decorate]")," attribute is very useful in scenarios where you cannot touch the ",(0,i.yg)("code",null,"#[Factory]")," method. This can happen if the ",(0,i.yg)("code",null,"#[Factory]")," method is defined in a third-party library or if the ",(0,i.yg)("code",null,"#[Factory]")," method is part of auto-generated code."),(0,i.yg)("p",null,"Let's assume you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Factory]")," to create the input type."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Assuming you ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,i.yg)("p",null,"A few things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,i.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,i.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Decorate]")," attribute must contain a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"#[Factory]"),' attribute, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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."))}s.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6481],{18650:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>l,default:()=>s,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"extend-input-type",title:"Extending an input type",sidebar_label:"Extending an input type"},l=void 0,o={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},d=[],u={toc:d},y="wrapper";function s(e){let{components:t,...n}=e;return(0,i.yg)(y,(0,a.A)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,i.yg)("code",null,"#[Factory]")," tag, ",(0,i.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,i.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,i.yg)("p",null,"Just like with output type (that can be ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/extend-type"},"extended using the ",(0,i.yg)("inlineCode",{parentName:"a"},"ExtendType")," attribute"),"), you can extend/modify\nan input type using the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Decorate]")," attribute."),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Decorate]")," attribute to add additional fields to an input type that is already declared by a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Factory]")," attribute,\nor to modify the returned object."),(0,i.yg)("div",{class:"alert alert--info"},"The ",(0,i.yg)("code",null,"#[Decorate]")," attribute is very useful in scenarios where you cannot touch the ",(0,i.yg)("code",null,"#[Factory]")," method. This can happen if the ",(0,i.yg)("code",null,"#[Factory]")," method is defined in a third-party library or if the ",(0,i.yg)("code",null,"#[Factory]")," method is part of auto-generated code."),(0,i.yg)("p",null,"Let's assume you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Factory]")," to create the input type."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Assuming you ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,i.yg)("p",null,"A few things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,i.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,i.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Decorate]")," attribute must contain a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"#[Factory]"),' attribute, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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."))}s.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/20540af3.5d51fb83.js b/assets/js/20540af3.0917bd96.js similarity index 99% rename from assets/js/20540af3.5d51fb83.js rename to assets/js/20540af3.0917bd96.js index e8e143f6d..9ef97195e 100644 --- a/assets/js/20540af3.5d51fb83.js +++ b/assets/js/20540af3.0917bd96.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4054],{94317:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>p,toc:()=>y});var n=a(58168),l=(a(96540),a(15680));a(67443);const r={id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},i=void 0,p={unversionedId:"annotations-reference",id:"version-7.0.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-7.0.0/annotations-reference.md",sourceDirName:".",slug:"/annotations-reference",permalink:"/docs/7.0.0/annotations-reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/annotations-reference.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/7.0.0/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/7.0.0/semver"}},g={},y=[{value:"@Query",id:"query",level:2},{value:"@Mutation",id:"mutation",level:2},{value:"@Subscription",id:"subscription",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}],o={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},o,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.yg)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.yg)("h2",{id:"query"},"@Query"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation"},"@Mutation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"subscription"},"@Subscription"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Subscription")," annotation is used to declare a GraphQL subscription."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the subscription. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Defines the GraphQL output type that will be sent for the subscription.")))),(0,l.yg)("h2",{id:"type"},"@Type"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("a",{parentName:"p",href:"#input-annotation"},"@Input annotation")," directly on the input type or a ",(0,l.yg)("a",{parentName:"p",href:"#factory-annotation"},"@Factory annoation")," to make/return an input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("em",{parentName:"td"},"is passed"),", ",(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/external-type-declaration"},"the class/enum annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," becomes a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.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.yg)("h2",{id:"extendtype"},"@ExtendType"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/extend-type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"input"},"@Input"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,l.yg)("inlineCode",{parentName:"td"},"true")," ",(0,l.yg)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,l.yg)("inlineCode",{parentName:"td"},"true")," when ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"update"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.yg)("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/subscription. This primarily applies to nullable fields.")))),(0,l.yg)("h2",{id:"field"},"@Field"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.yg)("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.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"for"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string, array"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/input-types"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.yg)("h2",{id:"sourcefield"},"@SourceField"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield"},"@MagicField"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"prefetch"},"@Prefetch"),(0,l.yg)("p",null,"Marks field parameter to be used for ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/prefetch-method"},"prefetching"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": parameters of methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"callable"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"callable"),(0,l.yg)("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.yg)("h2",{id:"logged"},"@Logged"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right"},"@Right"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith"},"@FailWith"),(0,l.yg)("p",null,"The ",(0,l.yg)("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/subscription/field (according to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"value"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized"},"@HideIfUnauthorized"),(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query/mutation/subscription/field if the user is not authorized\nto access it (according to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser"},"@InjectUser"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery/mutation/subscription/field."),(0,l.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/authentication-authorization"},"the authentication and authorization page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security"},"@Security"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory"},"@Factory"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype"},"@UseInputType"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate"},"@Decorate"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire"},"@Autowire"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter"},"@HideParameter"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"cost"},"@Cost"),(0,l.yg)("p",null,"Sets complexity and multipliers on fields for ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/operation-complexity#static-request-analysis"},"automatic query complexity"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"complexity")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"int"),(0,l.yg)("td",{parentName:"tr",align:null},"Complexity for that field")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"multipliers")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("td",{parentName:"tr",align:null},"Names of fields by value of which complexity will be multiplied")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"defaultMultiplier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"int"),(0,l.yg)("td",{parentName:"tr",align:null},"Default multiplier value if all multipliers are missing/null")))),(0,l.yg)("h2",{id:"validate"},"@Validate"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion"},"@Assertion"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype"},(0,l.yg)("del",{parentName:"h2"},"@EnumType")),(0,l.yg)("p",null,(0,l.yg)("em",{parentName:"p"},"Deprecated: Use ",(0,l.yg)("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.yg)("a",{parentName:"em",href:"#type-annotation"},"@Type"),".")),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4054],{94317:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>p,toc:()=>y});var n=a(58168),l=(a(96540),a(15680));a(67443);const r={id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},i=void 0,p={unversionedId:"annotations-reference",id:"version-7.0.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-7.0.0/annotations-reference.md",sourceDirName:".",slug:"/annotations-reference",permalink:"/docs/7.0.0/annotations-reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/annotations-reference.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/7.0.0/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/7.0.0/semver"}},g={},y=[{value:"@Query",id:"query",level:2},{value:"@Mutation",id:"mutation",level:2},{value:"@Subscription",id:"subscription",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}],o={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},o,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.yg)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.yg)("h2",{id:"query"},"@Query"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation"},"@Mutation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"subscription"},"@Subscription"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Subscription")," annotation is used to declare a GraphQL subscription."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the subscription. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Defines the GraphQL output type that will be sent for the subscription.")))),(0,l.yg)("h2",{id:"type"},"@Type"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("a",{parentName:"p",href:"#input-annotation"},"@Input annotation")," directly on the input type or a ",(0,l.yg)("a",{parentName:"p",href:"#factory-annotation"},"@Factory annoation")," to make/return an input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("em",{parentName:"td"},"is passed"),", ",(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/external-type-declaration"},"the class/enum annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," becomes a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.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.yg)("h2",{id:"extendtype"},"@ExtendType"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/extend-type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"input"},"@Input"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,l.yg)("inlineCode",{parentName:"td"},"true")," ",(0,l.yg)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,l.yg)("inlineCode",{parentName:"td"},"true")," when ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"update"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.yg)("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/subscription. This primarily applies to nullable fields.")))),(0,l.yg)("h2",{id:"field"},"@Field"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.yg)("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.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"for"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string, array"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/input-types"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.yg)("h2",{id:"sourcefield"},"@SourceField"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield"},"@MagicField"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"prefetch"},"@Prefetch"),(0,l.yg)("p",null,"Marks field parameter to be used for ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/prefetch-method"},"prefetching"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": parameters of methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"callable"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"callable"),(0,l.yg)("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.yg)("h2",{id:"logged"},"@Logged"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right"},"@Right"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith"},"@FailWith"),(0,l.yg)("p",null,"The ",(0,l.yg)("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/subscription/field (according to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"value"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized"},"@HideIfUnauthorized"),(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation is used to completely hide the query/mutation/subscription/field if the user is not authorized\nto access it (according to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser"},"@InjectUser"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to inject an instance of the current user logged in into a parameter of your\nquery/mutation/subscription/field."),(0,l.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/authentication-authorization"},"the authentication and authorization page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security"},"@Security"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory"},"@Factory"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("a",{parentName:"td",href:"/docs/7.0.0/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype"},"@UseInputType"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate"},"@Decorate"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire"},"@Autowire"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter"},"@HideParameter"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"cost"},"@Cost"),(0,l.yg)("p",null,"Sets complexity and multipliers on fields for ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/operation-complexity#static-request-analysis"},"automatic query complexity"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"complexity")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"int"),(0,l.yg)("td",{parentName:"tr",align:null},"Complexity for that field")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"multipliers")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("td",{parentName:"tr",align:null},"Names of fields by value of which complexity will be multiplied")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"defaultMultiplier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"int"),(0,l.yg)("td",{parentName:"tr",align:null},"Default multiplier value if all multipliers are missing/null")))),(0,l.yg)("h2",{id:"validate"},"@Validate"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion"},"@Assertion"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype"},(0,l.yg)("del",{parentName:"h2"},"@EnumType")),(0,l.yg)("p",null,(0,l.yg)("em",{parentName:"p"},"Deprecated: Use ",(0,l.yg)("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.yg)("a",{parentName:"em",href:"#type-annotation"},"@Type"),".")),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/21637dff.64b940b8.js b/assets/js/21637dff.7d2208c1.js similarity index 99% rename from assets/js/21637dff.64b940b8.js rename to assets/js/21637dff.7d2208c1.js index 753ac35d4..d49578707 100644 --- a/assets/js/21637dff.64b940b8.js +++ b/assets/js/21637dff.7d2208c1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9032],{19365:(e,n,t)=>{t.d(n,{A:()=>o});var a=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:n,hidden:t,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>I});var a=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function d(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 h(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??d(t);return function(e){const n=(0,s.X)(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 p(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,l.W6)(),i=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.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function m(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=h(e),[o,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(!p({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:i}))),[u,s]=g({queryString:t,groupId:a}),[d,m]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),y=(()=>{const e=u??d;return p({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),m(e)}),[s,m,i]),tabValues:i}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},p=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 r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function N(e){const n=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function I(e){const n=(0,y.A)();return r.createElement(N,(0,a.A)({key:String(n)},e))}},41080:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>g,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],h={toc:d},p="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(p,(0,a.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.yg)("a",{parentName:"li",href:"/docs/4.2/fine-grained-security"},(0,r.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.yg)("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.yg)("br",null),"See ",(0,r.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.yg)("h2",{id:"logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.yg)("p",null,"GraphQLite exposes two annotations (",(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the query ",(0,r.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.2/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.yg)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9032],{19365:(e,n,t)=>{t.d(n,{A:()=>o});var a=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:n,hidden:t,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>I});var a=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function d(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 h(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??d(t);return function(e){const n=(0,s.X)(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 p(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,l.W6)(),i=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.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function m(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=h(e),[o,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(!p({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:i}))),[u,s]=g({queryString:t,groupId:a}),[d,m]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),y=(()=>{const e=u??d;return p({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),m(e)}),[s,m,i]),tabValues:i}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},p=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 r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function N(e){const n=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function I(e){const n=(0,y.A)();return r.createElement(N,(0,a.A)({key:String(n)},e))}},41080:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>g,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],h={toc:d},p="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(p,(0,a.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.yg)("a",{parentName:"li",href:"/docs/4.2/fine-grained-security"},(0,r.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.yg)("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.yg)("br",null),"See ",(0,r.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.yg)("h2",{id:"logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.yg)("p",null,"GraphQLite exposes two annotations (",(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the query ",(0,r.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.2/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.yg)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/21a7a3b0.116eca1b.js b/assets/js/21a7a3b0.1330d704.js similarity index 99% rename from assets/js/21a7a3b0.116eca1b.js rename to assets/js/21a7a3b0.1330d704.js index f7bdc309e..338ec0f09 100644 --- a/assets/js/21a7a3b0.116eca1b.js +++ b/assets/js/21a7a3b0.1330d704.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3382],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>A});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),f=(()=>{const e=s??d;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),g(e)}),[u,g,i]),tabValues:i}}var f=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",y.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function A(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},67708:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>p,frontMatter:()=>i,metadata:()=>l,toc:()=>u});var n=a(58168),r=(a(96540),a(15680));a(67443),a(11470),a(19365);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/6.1/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/autowiring.mdx",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"docs",previous:{title:"Type mapping",permalink:"/docs/6.1/type-mapping"},next:{title:"Extending a type",permalink:"/docs/6.1/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.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n')),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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([[3382],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>A});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),f=(()=>{const e=s??d;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),g(e)}),[u,g,i]),tabValues:i}}var f=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",y.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function A(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},67708:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>p,frontMatter:()=>i,metadata:()=>l,toc:()=>u});var n=a(58168),r=(a(96540),a(15680));a(67443),a(11470),a(19365);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/6.1/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/autowiring.mdx",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"docs",previous:{title:"Type mapping",permalink:"/docs/6.1/type-mapping"},next:{title:"Extending a type",permalink:"/docs/6.1/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.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n')),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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.cb440bf0.js b/assets/js/21cde469.ef6b9adb.js similarity index 99% rename from assets/js/21cde469.cb440bf0.js rename to assets/js/21cde469.ef6b9adb.js index ad06a36c5..cf3cff96f 100644 --- a/assets/js/21cde469.cb440bf0.js +++ b/assets/js/21cde469.ef6b9adb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1653],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>w});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),c=t(31682),u=t(89466);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,c.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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,c]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,u.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),c(e),y(e)}),[c,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),h=e=>{const n=e.currentTarget,t=u.indexOf(n),r=c[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=u.indexOf(e.currentTarget)+1;n=u[t]??u[0];break}case"ArrowLeft":{const t=u.indexOf(e.currentTarget)-1;n=u[t]??u[u.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.A)("tabs__item",f.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 v(e){const n=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function w(e){const n=(0,m.A)();return a.createElement(v,(0,r.A)({key:String(n)},e))}},37088:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>c,toc:()=>p});var r=t(58168),a=(t(96540),t(15680)),o=(t(67443),t(11470)),i=t(19365);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,c={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},u={},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 g(e){let{components:n,...t}=e;return(0,a.yg)(d,(0,r.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.2/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/4.2/laravel-package"},"Laravel"),")."),(0,a.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1653],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>w});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),c=t(31682),u=t(89466);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,c.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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,c]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,u.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),c(e),y(e)}),[c,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),h=e=>{const n=e.currentTarget,t=u.indexOf(n),r=c[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=u.indexOf(e.currentTarget)+1;n=u[t]??u[0];break}case"ArrowLeft":{const t=u.indexOf(e.currentTarget)-1;n=u[t]??u[u.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.A)("tabs__item",f.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 v(e){const n=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function w(e){const n=(0,m.A)();return a.createElement(v,(0,r.A)({key:String(n)},e))}},37088:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>c,toc:()=>p});var r=t(58168),a=(t(96540),t(15680)),o=(t(67443),t(11470)),i=t(19365);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,c={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},u={},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 g(e){let{components:n,...t}=e;return(0,a.yg)(d,(0,r.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.2/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/4.2/laravel-package"},"Laravel"),")."),(0,a.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/22e1e32f.c82c5b5b.js b/assets/js/22e1e32f.08dbebdc.js similarity index 99% rename from assets/js/22e1e32f.c82c5b5b.js rename to assets/js/22e1e32f.08dbebdc.js index efbe264ee..3b1b3dddd 100644 --- a/assets/js/22e1e32f.c82c5b5b.js +++ b/assets/js/22e1e32f.08dbebdc.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3613],{16028:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>d,contentTitle:()=>r,default:()=>u,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var t=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function u(e){let{components:a,...n}=e;return(0,i.yg)(g,(0,t.A)({},s,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"500"},"5.0.0"),(0,i.yg)("h4",{id:"dependencies"},"Dependencies:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.yg)("h2",{id:"430"},"4.3.0"),(0,i.yg)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The method ",(0,i.yg)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.yg)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.yg)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.yg)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h4",{id:"new-features"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/input-types#input-attribute"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h4",{id:"new-features-1"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h4",{id:"new-features-2"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("h4",{id:"symfony"},"Symfony:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h4",{id:"laravel"},"Laravel:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h4",{id:"internals"},"Internals:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3613],{16028:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>d,contentTitle:()=>r,default:()=>u,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var t=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function u(e){let{components:a,...n}=e;return(0,i.yg)(g,(0,t.A)({},s,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"500"},"5.0.0"),(0,i.yg)("h4",{id:"dependencies"},"Dependencies:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.yg)("h2",{id:"430"},"4.3.0"),(0,i.yg)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The method ",(0,i.yg)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.yg)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.yg)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.yg)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h4",{id:"new-features"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/input-types#input-attribute"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h4",{id:"new-features-1"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h4",{id:"new-features-2"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("h4",{id:"symfony"},"Symfony:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h4",{id:"laravel"},"Laravel:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h4",{id:"internals"},"Internals:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/232afa3a.5a5417be.js b/assets/js/232afa3a.11ff0b56.js similarity index 99% rename from assets/js/232afa3a.5a5417be.js rename to assets/js/232afa3a.11ff0b56.js index d26f3a38c..c18ff1765 100644 --- a/assets/js/232afa3a.5a5417be.js +++ b/assets/js/232afa3a.11ff0b56.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4762],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),u=a(56347),i=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),g=(()=>{const e=i??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&u(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}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var g=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},41002:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);const u={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},i=void 0,s={unversionedId:"file-uploads",id:"version-7.0.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-7.0.0/file-uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/7.0.0/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/file-uploads.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"docs",previous:{title:"Automatic persisted queries",permalink:"/docs/7.0.0/automatic-persisted-queries"},next:{title:"Pagination",permalink:"/docs/7.0.0/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.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.yg)("p",null,"You must start by installing this package:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.yg)("p",null,"In order to use this, you must first be sure that the ",(0,r.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.yg)("pre",null,(0,r.yg)("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([[4762],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),u=a(56347),i=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),g=(()=>{const e=i??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&u(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}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var g=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},41002:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);const u={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},i=void 0,s={unversionedId:"file-uploads",id:"version-7.0.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-7.0.0/file-uploads.mdx",sourceDirName:".",slug:"/file-uploads",permalink:"/docs/7.0.0/file-uploads",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/file-uploads.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"docs",previous:{title:"Automatic persisted queries",permalink:"/docs/7.0.0/automatic-persisted-queries"},next:{title:"Pagination",permalink:"/docs/7.0.0/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.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.yg)("p",null,"You must start by installing this package:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.yg)("p",null,"In order to use this, you must first be sure that the ",(0,r.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.yg)("pre",null,(0,r.yg)("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/2355609d.52420cde.js b/assets/js/2355609d.7d53c238.js similarity index 98% rename from assets/js/2355609d.52420cde.js rename to assets/js/2355609d.7d53c238.js index a36c197e5..9e65ba81d 100644 --- a/assets/js/2355609d.52420cde.js +++ b/assets/js/2355609d.7d53c238.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6145],{24197:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/4.3/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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([[6145],{24197:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/4.3/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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.7217b836.js b/assets/js/23794275.b58c4864.js similarity index 99% rename from assets/js/23794275.7217b836.js rename to assets/js/23794275.b58c4864.js index 551da92bf..f5fa71279 100644 --- a/assets/js/23794275.7217b836.js +++ b/assets/js/23794275.b58c4864.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1776],{19365:(e,n,a)=>{a.d(n,{A:()=>r});var t=a(96540),p=a(20053);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:a,className:r}=e;return t.createElement("div",{role:"tabpanel",className:(0,p.A)(l.tabItem,r),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>N});var t=a(58168),p=a(96540),l=a(20053),r=a(23104),s=a(56347),i=a(57485),u=a(31682),o=a(89466);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:a,attributes:t,default:p}}=e;return{value:n,label:a,attributes:t,default:p}}))}function m(e){const{values:n,children:a}=e;return(0,p.useMemo)((()=>{const e=n??c(a);return function(e){const n=(0,u.X)(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,a])}function y(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,i.aZ)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function g(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!y({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[i,u]=d({queryString:a,groupId:t}),[c,g]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,p.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=i??c;return y({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{h&&s(h)}),[h]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!y({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 h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=u[a].value;t!==s&&(c(n),i(t))},y=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},u.map((e=>{let{value:n,label:a,attributes:r}=e;return p.createElement("li",(0,t.A)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:y,onClick:m},r,{className:(0,l.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function T(e){const n=g(e);return p.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},p.createElement(b,(0,t.A)({},e,n)),p.createElement(v,(0,t.A)({},e,n)))}function N(e){const n=(0,h.A)();return p.createElement(T,(0,t.A)({key:String(n)},e))}},22793:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>i,default:()=>d,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var t=a(58168),p=(a(96540),a(15680)),l=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/6.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/6.0/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"Union types for return are supported in GraphQLite as of version 6.0:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"name")," property on the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," annotation:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,p.yg)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,p.yg)("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.yg)("p",null,(0,p.yg)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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([[1776],{19365:(e,n,a)=>{a.d(n,{A:()=>r});var t=a(96540),p=a(20053);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:a,className:r}=e;return t.createElement("div",{role:"tabpanel",className:(0,p.A)(l.tabItem,r),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>N});var t=a(58168),p=a(96540),l=a(20053),r=a(23104),s=a(56347),i=a(57485),u=a(31682),o=a(89466);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:a,attributes:t,default:p}}=e;return{value:n,label:a,attributes:t,default:p}}))}function m(e){const{values:n,children:a}=e;return(0,p.useMemo)((()=>{const e=n??c(a);return function(e){const n=(0,u.X)(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,a])}function y(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,i.aZ)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function g(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!y({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[i,u]=d({queryString:a,groupId:t}),[c,g]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,p.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=i??c;return y({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{h&&s(h)}),[h]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!y({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 h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=u[a].value;t!==s&&(c(n),i(t))},y=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},u.map((e=>{let{value:n,label:a,attributes:r}=e;return p.createElement("li",(0,t.A)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:y,onClick:m},r,{className:(0,l.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function T(e){const n=g(e);return p.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},p.createElement(b,(0,t.A)({},e,n)),p.createElement(v,(0,t.A)({},e,n)))}function N(e){const n=(0,h.A)();return p.createElement(T,(0,t.A)({key:String(n)},e))}},22793:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>i,default:()=>d,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var t=a(58168),p=(a(96540),a(15680)),l=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/6.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/6.0/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"Union types for return are supported in GraphQLite as of version 6.0:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"name")," property on the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," annotation:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,p.yg)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,p.yg)("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.yg)("p",null,(0,p.yg)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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/23a8ac29.22cce971.js b/assets/js/23a8ac29.a124ce1b.js similarity index 99% rename from assets/js/23a8ac29.22cce971.js rename to assets/js/23a8ac29.a124ce1b.js index 4c3289d79..cf35bcb3e 100644 --- a/assets/js/23a8ac29.22cce971.js +++ b/assets/js/23a8ac29.a124ce1b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1950],{19365:(e,a,t)=>{t.d(a,{A:()=>o});var n=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:a,hidden:t,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>V});var n=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),s=t(57485),u=t(31682),d=t(89466);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function c(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??p(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function m(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:t}=e;const n=(0,l.W6)(),i=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const a=new URLSearchParams(n.location.search);a.set(i,e),n.replace({...n.location,search:a.toString()})}),[i,n])]}function y(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!m({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:i}))),[s,u]=h({queryString:t,groupId:n}),[p,y]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,i]=(0,d.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:n}),g=(()=>{const e=s??p;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),y(e)}),[u,y,i]),tabValues:i}}var g=t(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:a,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),c=e=>{const a=e.currentTarget,t=d.indexOf(a),n=u[t].value;n!==l&&(p(a),s(n))},m=e=>{let a=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const t=d.indexOf(e.currentTarget)+1;a=d[t]??d[0];break}case"ArrowLeft":{const t=d.indexOf(e.currentTarget)-1;a=d[t]??d[d.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.A)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=y(e);return r.createElement("div",{className:(0,i.A)("tabs-container",v.tabList)},r.createElement(f,(0,n.A)({},e,a)),r.createElement(b,(0,n.A)({},e,a)))}function V(e){const a=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},2192:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,r.yg)(m,(0,n.A)({},c,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,r.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.yg)("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.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.yg)("p",null,"You can also pass an array to the ",(0,r.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.yg)("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([[1950],{19365:(e,a,t)=>{t.d(a,{A:()=>o});var n=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:a,hidden:t,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>V});var n=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),s=t(57485),u=t(31682),d=t(89466);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function c(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??p(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function m(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:t}=e;const n=(0,l.W6)(),i=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const a=new URLSearchParams(n.location.search);a.set(i,e),n.replace({...n.location,search:a.toString()})}),[i,n])]}function y(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!m({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:i}))),[s,u]=h({queryString:t,groupId:n}),[p,y]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,i]=(0,d.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:n}),g=(()=>{const e=s??p;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),y(e)}),[u,y,i]),tabValues:i}}var g=t(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:a,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),c=e=>{const a=e.currentTarget,t=d.indexOf(a),n=u[t].value;n!==l&&(p(a),s(n))},m=e=>{let a=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const t=d.indexOf(e.currentTarget)+1;a=d[t]??d[0];break}case"ArrowLeft":{const t=d.indexOf(e.currentTarget)-1;a=d[t]??d[d.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.A)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=y(e);return r.createElement("div",{className:(0,i.A)("tabs-container",v.tabList)},r.createElement(f,(0,n.A)({},e,a)),r.createElement(b,(0,n.A)({},e,a)))}function V(e){const a=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},2192:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,r.yg)(m,(0,n.A)({},c,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,r.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.yg)("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.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.yg)("p",null,"You can also pass an array to the ",(0,r.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.yg)("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.ea8060e2.js b/assets/js/23f642f2.1564dfe4.js similarity index 99% rename from assets/js/23f642f2.ea8060e2.js rename to assets/js/23f642f2.1564dfe4.js index f07baae57..0fafb7c75 100644 --- a/assets/js/23f642f2.ea8060e2.js +++ b/assets/js/23f642f2.1564dfe4.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2964],{19365:(e,t,n)=>{n.d(t,{A:()=>l});var a=n(96540),r=n(20053);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.A)(o.tabItem,l),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>T});var a=n(58168),r=n(96540),o=n(20053),l=n(23104),u=n(56347),i=n(57485),p=n(31682),s=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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,u.W6)(),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.aZ)(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 m(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(!y({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]=h({queryString:n,groupId:a}),[c,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,s.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),g=(()=>{const e=i??c;return y({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{g&&u(g)}),[g]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);u(e),p(e),m(e)}),[p,m,o]),tabValues:o}}var g=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:u,selectValue:i,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.a_)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==u&&(c(t),i(a))},y=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.A)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},l,{className:(0,o.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":u===t})}),n??t)})))}function v(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 P(e){const t=m(e);return r.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function T(e){const t=(0,g.A)();return r.createElement(P,(0,a.A)({key:String(t)},e))}},64417:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>p,toc:()=>c});var a=n(58168),r=(n(96540),n(15680)),o=(n(67443),n(11470)),l=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:t,...n}=e;return(0,r.yg)(y,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Let's admit you are developing an API that returns a list of cities around a location."),(0,r.yg)("p",null,"Your GraphQL query might look like this:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,r.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,r.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,r.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,r.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,r.yg)("p",null,"In order to declare that type, in GraphQLite, we will declare a ",(0,r.yg)("strong",{parentName:"p"},"Factory"),"."),(0,r.yg)("p",null,"A ",(0,r.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,r.yg)("p",null,"Here is an example of factory:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,r.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,r.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,r.yg)("p",null,"A few important things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,r.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,r.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,r.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")))),(0,r.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,r.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,r.yg)("p",null,"Here is an annotated sample:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("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.yg)("p",null,"Image your ",(0,r.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,r.yg)("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.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,r.yg)("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([[2964],{19365:(e,t,n)=>{n.d(t,{A:()=>l});var a=n(96540),r=n(20053);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.A)(o.tabItem,l),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>T});var a=n(58168),r=n(96540),o=n(20053),l=n(23104),u=n(56347),i=n(57485),p=n(31682),s=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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,u.W6)(),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.aZ)(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 m(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(!y({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]=h({queryString:n,groupId:a}),[c,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,s.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),g=(()=>{const e=i??c;return y({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{g&&u(g)}),[g]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);u(e),p(e),m(e)}),[p,m,o]),tabValues:o}}var g=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:u,selectValue:i,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.a_)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==u&&(c(t),i(a))},y=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.A)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:u===t?0:-1,"aria-selected":u===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},l,{className:(0,o.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":u===t})}),n??t)})))}function v(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 P(e){const t=m(e);return r.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function T(e){const t=(0,g.A)();return r.createElement(P,(0,a.A)({key:String(t)},e))}},64417:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>p,toc:()=>c});var a=n(58168),r=(n(96540),n(15680)),o=(n(67443),n(11470)),l=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:t,...n}=e;return(0,r.yg)(y,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Let's admit you are developing an API that returns a list of cities around a location."),(0,r.yg)("p",null,"Your GraphQL query might look like this:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,r.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,r.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,r.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,r.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,r.yg)("p",null,"In order to declare that type, in GraphQLite, we will declare a ",(0,r.yg)("strong",{parentName:"p"},"Factory"),"."),(0,r.yg)("p",null,"A ",(0,r.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,r.yg)("p",null,"Here is an example of factory:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,r.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,r.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,r.yg)("p",null,"A few important things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,r.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,r.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,r.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"#[Factory]\npublic function createLocation(float $latitude, float $longitude): Location\n{\n return new Location($latitude, $longitude);\n}\n")))),(0,r.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,r.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,r.yg)("p",null,"Here is an annotated sample:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("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.yg)("p",null,"Image your ",(0,r.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,r.yg)("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.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,r.yg)("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/242d99d9.3f57a286.js b/assets/js/242d99d9.76f7b35a.js similarity index 97% rename from assets/js/242d99d9.3f57a286.js rename to assets/js/242d99d9.76f7b35a.js index c2188a1ae..d8d353665 100644 --- a/assets/js/242d99d9.3f57a286.js +++ b/assets/js/242d99d9.76f7b35a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3088],{92522:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>p,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],g={toc:u},c="wrapper";function p(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},g,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3088],{92522:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>p,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],g={toc:u},c="wrapper";function p(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},g,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/24ac61c7.b7e599f7.js b/assets/js/24ac61c7.7b8c1194.js similarity index 98% rename from assets/js/24ac61c7.b7e599f7.js rename to assets/js/24ac61c7.7b8c1194.js index 50678ed10..8a6c683f6 100644 --- a/assets/js/24ac61c7.b7e599f7.js +++ b/assets/js/24ac61c7.7b8c1194.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9008],{35313:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>s,default:()=>h,frontMatter:()=>r,metadata:()=>l,toc:()=>c});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.yg)("p",null,"Written in ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types would look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.yg)("p",null,"The GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.yg)("div",{class:"alert alert--warning"},"Right now, there is no way to explicitly declare a GraphQL interface using GraphQLite.",(0,i.yg)("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([[9008],{35313:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>s,default:()=>h,frontMatter:()=>r,metadata:()=>l,toc:()=>c});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.yg)("p",null,"Written in ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types would look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.yg)("p",null,"The GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.yg)("div",{class:"alert alert--warning"},"Right now, there is no way to explicitly declare a GraphQL interface using GraphQLite.",(0,i.yg)("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.920d2cd9.js b/assets/js/24aca886.5ba7e1af.js similarity index 99% rename from assets/js/24aca886.920d2cd9.js rename to assets/js/24aca886.5ba7e1af.js index 3897929a1..3a534a4d3 100644 --- a/assets/js/24aca886.920d2cd9.js +++ b/assets/js/24aca886.5ba7e1af.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3820],{6874:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/4.0/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.0/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3820],{6874:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/4.0/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.0/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/25d4129e.6df76c9d.js b/assets/js/25d4129e.68e7b119.js similarity index 99% rename from assets/js/25d4129e.6df76c9d.js rename to assets/js/25d4129e.68e7b119.js index 14eaf075c..ead130307 100644 --- a/assets/js/25d4129e.6df76c9d.js +++ b/assets/js/25d4129e.68e7b119.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2459],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>w});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),c=t(31682),u=t(89466);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,c.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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,c]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,u.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),c(e),y(e)}),[c,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),h=e=>{const n=e.currentTarget,t=u.indexOf(n),r=c[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=u.indexOf(e.currentTarget)+1;n=u[t]??u[0];break}case"ArrowLeft":{const t=u.indexOf(e.currentTarget)-1;n=u[t]??u[u.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.A)("tabs__item",f.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 v(e){const n=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function w(e){const n=(0,m.A)();return a.createElement(v,(0,r.A)({key:String(n)},e))}},46065:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>c,toc:()=>p});var r=t(58168),a=(t(96540),t(15680)),o=(t(67443),t(11470)),i=t(19365);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,c={unversionedId:"error-handling",id:"version-7.0.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-7.0.0/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/7.0.0/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/error-handling.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/7.0.0/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/7.0.0/validation"}},u={},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 g(e){let{components:n,...t}=e;return(0,a.yg)(d,(0,r.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/7.0.0/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/7.0.0/laravel-package"},"Laravel"),")."),(0,a.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2459],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>w});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),c=t(31682),u=t(89466);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,c.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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,c]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,u.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),c(e),y(e)}),[c,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),h=e=>{const n=e.currentTarget,t=u.indexOf(n),r=c[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=u.indexOf(e.currentTarget)+1;n=u[t]??u[0];break}case"ArrowLeft":{const t=u.indexOf(e.currentTarget)-1;n=u[t]??u[u.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.A)("tabs__item",f.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 v(e){const n=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function w(e){const n=(0,m.A)();return a.createElement(v,(0,r.A)({key:String(n)},e))}},46065:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>c,toc:()=>p});var r=t(58168),a=(t(96540),t(15680)),o=(t(67443),t(11470)),i=t(19365);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,c={unversionedId:"error-handling",id:"version-7.0.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-7.0.0/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/7.0.0/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/error-handling.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/7.0.0/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/7.0.0/validation"}},u={},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 g(e){let{components:n,...t}=e;return(0,a.yg)(d,(0,r.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/7.0.0/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/7.0.0/laravel-package"},"Laravel"),")."),(0,a.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/263ebc7a.67b2a230.js b/assets/js/263ebc7a.12eb452f.js similarity index 99% rename from assets/js/263ebc7a.67b2a230.js rename to assets/js/263ebc7a.12eb452f.js index a9932a31f..8c437daaa 100644 --- a/assets/js/263ebc7a.67b2a230.js +++ b/assets/js/263ebc7a.12eb452f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3642],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(i.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),i=n(20053),o=n(23104),s=n(56347),u=n(57485),l=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function p(e){let{queryString:t=!1,groupId:n}=e;const a=(0,s.W6)(),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.aZ)(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 m(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(!g({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]=p({queryString:n,groupId:a}),[d,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),y=(()=>{const e=u??d;return g({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&s(y)}),[y]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);s(e),l(e),m(e)}),[l,m,i]),tabValues:i}}var y=n(92303);const f={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.a_)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=l[n].value;a!==s&&(d(t),u(a))},g=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.A)("tabs",{"tabs--block":n},t)},l.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:h},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":s===t})}),n??t)})))}function v(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=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,y.A)();return r.createElement(N,(0,a.A)({key:String(t)},e))}},55123:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>h,frontMatter:()=>i,metadata:()=>s,toc:()=>l});var a=n(58168),r=(n(96540),n(15680));n(67443),n(11470),n(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"docs",previous:{title:"User input validation",permalink:"/docs/6.1/validation"},next:{title:"Fine grained security",permalink:"/docs/6.1/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.yg)(d,(0,a.A)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.yg)("a",{parentName:"li",href:"/docs/6.1/fine-grained-security"},(0,r.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.yg)("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.yg)("br",null),"See ",(0,r.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.yg)("h2",{id:"logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.yg)("p",null,"GraphQLite exposes two annotations (",(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the query ",(0,r.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/6.1/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.yg)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("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([[3642],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(i.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),i=n(20053),o=n(23104),s=n(56347),u=n(57485),l=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function p(e){let{queryString:t=!1,groupId:n}=e;const a=(0,s.W6)(),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.aZ)(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 m(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(!g({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]=p({queryString:n,groupId:a}),[d,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),y=(()=>{const e=u??d;return g({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&s(y)}),[y]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);s(e),l(e),m(e)}),[l,m,i]),tabValues:i}}var y=n(92303);const f={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.a_)(),h=e=>{const t=e.currentTarget,n=c.indexOf(t),a=l[n].value;a!==s&&(d(t),u(a))},g=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.A)("tabs",{"tabs--block":n},t)},l.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:h},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":s===t})}),n??t)})))}function v(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=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,y.A)();return r.createElement(N,(0,a.A)({key:String(t)},e))}},55123:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>h,frontMatter:()=>i,metadata:()=>s,toc:()=>l});var a=n(58168),r=(n(96540),n(15680));n(67443),n(11470),n(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"docs",previous:{title:"User input validation",permalink:"/docs/6.1/validation"},next:{title:"Fine grained security",permalink:"/docs/6.1/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.yg)(d,(0,a.A)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.yg)("a",{parentName:"li",href:"/docs/6.1/fine-grained-security"},(0,r.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.yg)("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.yg)("br",null),"See ",(0,r.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.yg)("h2",{id:"logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.yg)("p",null,"GraphQLite exposes two annotations (",(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the query ",(0,r.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/6.1/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.yg)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("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.0e9e02ad.js b/assets/js/26662da3.df295bf1.js similarity index 99% rename from assets/js/26662da3.0e9e02ad.js rename to assets/js/26662da3.df295bf1.js index 4d269e858..25cb79297 100644 --- a/assets/js/26662da3.0e9e02ad.js +++ b/assets/js/26662da3.df295bf1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7321],{16591:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"}},l={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/3.0/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/3.0/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7321],{16591:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"}},l={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/3.0/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/3.0/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/26a27afb.82b76686.js b/assets/js/26a27afb.2468a3db.js similarity index 99% rename from assets/js/26a27afb.82b76686.js rename to assets/js/26a27afb.2468a3db.js index 07fc3b5e8..8c4f59fa2 100644 --- a/assets/js/26a27afb.82b76686.js +++ b/assets/js/26a27afb.2468a3db.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4954],{1656:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,i.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Now, go to the ",(0,i.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,i.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,i.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Now, go to the ",(0,i.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,i.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>r,metadata:()=>y,toc:()=>i});var n=a(58168),p=(a(96540),a(15680));a(67443);const r={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},o=void 0,y={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/next/pagination"},next:{title:"Custom attributes",permalink:"/docs/next/field-middlewares"}},l={},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}],s={toc:i},u="wrapper";function c(e){let{components:t,...a}=e;return(0,p.yg)(u,(0,n.A)({},s,a,{components:t,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.yg)("p",null,"GraphQL comes with an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n')),(0,p.yg)("h2",{id:"usage"},"Usage"),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.yg)("p",null,"You can use the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Query]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Mutation]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Subscription]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Field]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[SourceField]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[MagicField]"))),(0,p.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.yg)("p",null,"In order to create a custom output type, you need to:"),(0,p.yg)("ol",null,(0,p.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,p.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.yg)("p",null,"You'll find more details on the ",(0,p.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,p.yg)("hr",null),(0,p.yg)("p",null,"In order to find existing types, the schema is using ",(0,p.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,p.yg)("p",null,"Any class extending ",(0,p.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.yg)("p",null,"The easiest way is to use a ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,p.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,p.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,p.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},"create a ",(0,p.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,p.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,p.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,p.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,p.yg)("p",null,"RootTypeMapper are organized ",(0,p.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,p.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("p",null,"Now, in order to create an instance of your ",(0,p.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,p.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,p.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,p.yg)("p",null,"You can register your own root mapper factories using the ",(0,p.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,p.yg)("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([[1985],{1273:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>r,metadata:()=>y,toc:()=>i});var n=a(58168),p=(a(96540),a(15680));a(67443);const r={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},o=void 0,y={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/next/pagination"},next:{title:"Custom attributes",permalink:"/docs/next/field-middlewares"}},l={},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}],s={toc:i},u="wrapper";function c(e){let{components:t,...a}=e;return(0,p.yg)(u,(0,n.A)({},s,a,{components:t,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.yg)("p",null,"GraphQL comes with an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n')),(0,p.yg)("h2",{id:"usage"},"Usage"),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.yg)("p",null,"You can use the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Query]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Mutation]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Subscription]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Field]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[SourceField]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[MagicField]"))),(0,p.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.yg)("p",null,"In order to create a custom output type, you need to:"),(0,p.yg)("ol",null,(0,p.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,p.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.yg)("p",null,"You'll find more details on the ",(0,p.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,p.yg)("hr",null),(0,p.yg)("p",null,"In order to find existing types, the schema is using ",(0,p.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,p.yg)("p",null,"Any class extending ",(0,p.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.yg)("p",null,"The easiest way is to use a ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,p.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,p.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,p.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},"create a ",(0,p.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,p.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,p.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,p.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,p.yg)("p",null,"RootTypeMapper are organized ",(0,p.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,p.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("p",null,"Now, in order to create an instance of your ",(0,p.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,p.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,p.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,p.yg)("p",null,"You can register your own root mapper factories using the ",(0,p.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,p.yg)("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/27b414e3.42dc98ea.js b/assets/js/27b414e3.69a4785b.js similarity index 99% rename from assets/js/27b414e3.42dc98ea.js rename to assets/js/27b414e3.69a4785b.js index 4bebfcda3..61b56d898 100644 --- a/assets/js/27b414e3.42dc98ea.js +++ b/assets/js/27b414e3.69a4785b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5923],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var r=a(96540),t=a(20053);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,t.A)(o.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>$});var r=a(58168),t=a(96540),o=a(20053),i=a(23104),l=a(56347),s=a(57485),c=a(31682),p=a(89466);function u(e){return function(e){return t.Children.map(e,(e=>{if(!e||(0,t.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:a,attributes:r,default:t}}=e;return{value:n,label:a,attributes:r,default:t}}))}function d(e){const{values:n,children:a}=e;return(0,t.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function h(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:a}=e;const r=(0,l.W6)(),o=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(o),(0,t.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 y(e){const{defaultValue:n,queryString:a=!1,groupId:r}=e,o=d(e),[i,l]=(0,t.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,c]=m({queryString:a,groupId:r}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,p.Dv)(a);return[r,(0,t.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:r}),g=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,t.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:i,selectValue:(0,t.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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),d=e=>{const n=e.currentTarget,a=p.indexOf(n),r=c[a].value;r!==l&&(u(n),s(r))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;n=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;n=p[a]??p[p.length-1];break}}n?.focus()};return t.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return t.createElement("li",(0,r.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":l===n})}),a??n)})))}function w(e){let{lazy:n,children:a,selectedValue:r}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,t.cloneElement)(e,{className:"margin-top--md"}):null}return t.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,t.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=y(e);return t.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},t.createElement(b,(0,r.A)({},e,n)),t.createElement(w,(0,r.A)({},e,n)))}function $(e){const n=(0,g.A)();return t.createElement(v,(0,r.A)({key:String(n)},e))}},74665:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var r=a(58168),t=(a(96540),a(15680)),o=(a(67443),a(11470)),i=a(19365);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-7.0.0/other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/versioned_docs/version-7.0.0/other-frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/7.0.0/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/other-frameworks.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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/7.0.0/universal-service-providers"},next:{title:"Queries",permalink:"/docs/7.0.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:n,...a}=e;return(0,t.yg)(h,(0,r.A)({},d,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.laminas.dev/laminas-stratigility/"},"Laminas Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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 "laminas/laminas-diactoros": "^2",\n "laminas/laminas-stratigility": "^3",\n "laminas/laminas-httphandlerrunner": "^2",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Laminas ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Laminas Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,t.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("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([[5923],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var r=a(96540),t=a(20053);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,t.A)(o.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>$});var r=a(58168),t=a(96540),o=a(20053),i=a(23104),l=a(56347),s=a(57485),c=a(31682),p=a(89466);function u(e){return function(e){return t.Children.map(e,(e=>{if(!e||(0,t.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:a,attributes:r,default:t}}=e;return{value:n,label:a,attributes:r,default:t}}))}function d(e){const{values:n,children:a}=e;return(0,t.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function h(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:a}=e;const r=(0,l.W6)(),o=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(o),(0,t.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 y(e){const{defaultValue:n,queryString:a=!1,groupId:r}=e,o=d(e),[i,l]=(0,t.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,c]=m({queryString:a,groupId:r}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,p.Dv)(a);return[r,(0,t.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:r}),g=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,t.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:i,selectValue:(0,t.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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),d=e=>{const n=e.currentTarget,a=p.indexOf(n),r=c[a].value;r!==l&&(u(n),s(r))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;n=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;n=p[a]??p[p.length-1];break}}n?.focus()};return t.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return t.createElement("li",(0,r.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":l===n})}),a??n)})))}function w(e){let{lazy:n,children:a,selectedValue:r}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,t.cloneElement)(e,{className:"margin-top--md"}):null}return t.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,t.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=y(e);return t.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},t.createElement(b,(0,r.A)({},e,n)),t.createElement(w,(0,r.A)({},e,n)))}function $(e){const n=(0,g.A)();return t.createElement(v,(0,r.A)({key:String(n)},e))}},74665:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var r=a(58168),t=(a(96540),a(15680)),o=(a(67443),a(11470)),i=a(19365);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-7.0.0/other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/versioned_docs/version-7.0.0/other-frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/7.0.0/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/other-frameworks.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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/7.0.0/universal-service-providers"},next:{title:"Queries",permalink:"/docs/7.0.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:n,...a}=e;return(0,t.yg)(h,(0,r.A)({},d,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.laminas.dev/laminas-stratigility/"},"Laminas Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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 "laminas/laminas-diactoros": "^2",\n "laminas/laminas-stratigility": "^3",\n "laminas/laminas-httphandlerrunner": "^2",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Laminas ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Laminas Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,t.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("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/2830ce57.e1138f0b.js b/assets/js/2830ce57.b230beae.js similarity index 99% rename from assets/js/2830ce57.e1138f0b.js rename to assets/js/2830ce57.b230beae.js index be9c1b9f9..324eb8f64 100644 --- a/assets/js/2830ce57.e1138f0b.js +++ b/assets/js/2830ce57.b230beae.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9368],{20571:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);const r={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},l=void 0,o={unversionedId:"extend-type",id:"version-8.0.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-8.0.0/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-8.0.0/extend-type.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},p=[],d={toc:p},c="wrapper";function u(e){let{components:n,...t}=e;return(0,i.yg)(c,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute to add additional fields to a type that is already declared."),(0,i.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,i.yg)("p",null,"Let's assume you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,i.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Using ",(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]"),", you can add an additional ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Let's break this sample:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,i.yg)("p",null,"With the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,i.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]"),' attribute is used to add the "name" field to the ',(0,i.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,i.yg)("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.yg)("p",null,'Using the "',(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,i.yg)("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([[9368],{20571:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);const r={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},l=void 0,o={unversionedId:"extend-type",id:"version-8.0.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-8.0.0/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-8.0.0/extend-type.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},p=[],d={toc:p},c="wrapper";function u(e){let{components:n,...t}=e;return(0,i.yg)(c,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute to add additional fields to a type that is already declared."),(0,i.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,i.yg)("p",null,"Let's assume you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,i.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Using ",(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]"),", you can add an additional ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Let's break this sample:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,i.yg)("p",null,"With the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,i.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]"),' attribute is used to add the "name" field to the ',(0,i.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,i.yg)("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.yg)("p",null,'Using the "',(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,i.yg)("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/28c12eaf.a6253d51.js b/assets/js/28c12eaf.97fc0087.js similarity index 99% rename from assets/js/28c12eaf.a6253d51.js rename to assets/js/28c12eaf.97fc0087.js index 145f0b53a..54ba19bb1 100644 --- a/assets/js/28c12eaf.a6253d51.js +++ b/assets/js/28c12eaf.97fc0087.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6931],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>v});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),u=t(31682),c=t(89466);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.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),y(e)}),[u,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),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.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({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.A)("tabs__item",f.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=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function v(e){const n=(0,m.A)();return a.createElement(w,(0,r.A)({key:String(n)},e))}},93223:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var r=t(58168),a=(t(96540),t(15680));t(67443),t(11470),t(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/6.1/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/6.1/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.yg)(p,(0,r.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/6.1/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/6.1/laravel-package"},"Laravel"),")."),(0,a.yg)("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([[6931],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>v});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),u=t(31682),c=t(89466);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.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),y(e)}),[u,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),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.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({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.A)("tabs__item",f.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=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function v(e){const n=(0,m.A)();return a.createElement(w,(0,r.A)({key:String(n)},e))}},93223:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var r=t(58168),a=(t(96540),t(15680));t(67443),t(11470),t(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/6.1/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/6.1/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.yg)(p,(0,r.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/6.1/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/6.1/laravel-package"},"Laravel"),")."),(0,a.yg)("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/2917b31e.ba066590.js b/assets/js/2917b31e.50d9064f.js similarity index 99% rename from assets/js/2917b31e.ba066590.js rename to assets/js/2917b31e.50d9064f.js index 745aa770c..a6baca106 100644 --- a/assets/js/2917b31e.ba066590.js +++ b/assets/js/2917b31e.50d9064f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8735],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),u=a(57485),s=a(31682),i=a(89466);function y(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??y(a);return function(e){const t=(0,s.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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(!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}),[y,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=u??y;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:u,tabValues:s}=e;const i=[],{blockElementScrollPositionUntilNextRender:y}=(0,o.a_)(),c=e=>{const t=e.currentTarget,a=i.indexOf(t),n=s[a].value;n!==l&&(y(t),u(n))},d=e=>{let t=null;switch(e.key){case"Enter":c(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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:c},o,{className:(0,p.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},65352:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>y});var n=a(58168),r=(a(96540),a(15680)),p=(a(67443),a(11470)),o=a(19365);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},u=void 0,s={unversionedId:"custom-types",id:"version-7.0.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-7.0.0/custom-types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/7.0.0/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/custom-types.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/7.0.0/pagination"},next:{title:"Custom annotations",permalink:"/docs/7.0.0/field-middlewares"}},i={},y=[{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}],c={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Subscription")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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([[8735],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),u=a(57485),s=a(31682),i=a(89466);function y(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??y(a);return function(e){const t=(0,s.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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(!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}),[y,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=u??y;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:u,tabValues:s}=e;const i=[],{blockElementScrollPositionUntilNextRender:y}=(0,o.a_)(),c=e=>{const t=e.currentTarget,a=i.indexOf(t),n=s[a].value;n!==l&&(y(t),u(n))},d=e=>{let t=null;switch(e.key){case"Enter":c(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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:c},o,{className:(0,p.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},65352:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>u,default:()=>m,frontMatter:()=>l,metadata:()=>s,toc:()=>y});var n=a(58168),r=(a(96540),a(15680)),p=(a(67443),a(11470)),o=a(19365);const l={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},u=void 0,s={unversionedId:"custom-types",id:"version-7.0.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-7.0.0/custom-types.mdx",sourceDirName:".",slug:"/custom-types",permalink:"/docs/7.0.0/custom-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/custom-types.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/7.0.0/pagination"},next:{title:"Custom annotations",permalink:"/docs/7.0.0/field-middlewares"}},i={},y=[{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}],c={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Subscription")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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/29a6c1ba.2f241f7d.js b/assets/js/29a6c1ba.c9e9fd52.js similarity index 99% rename from assets/js/29a6c1ba.2f241f7d.js rename to assets/js/29a6c1ba.c9e9fd52.js index 8e37b1834..84a957eea 100644 --- a/assets/js/29a6c1ba.2f241f7d.js +++ b/assets/js/29a6c1ba.c9e9fd52.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8042],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),l=a(20053);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.A)(u.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>P});var n=a(58168),l=a(96540),u=a(20053),r=a(23104),i=a(56347),o=a(57485),p=a(31682),s=a(89466);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:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function d(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,p.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=d(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(!y({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]=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,u]=(0,s.Dv)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),g=(()=>{const e=o??c;return y({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),h(e)}),[p,h,u]),tabValues:u}}var g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),d=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(c(t),o(n))},y=e=>{let t=null;switch(e.key){case"Enter":d(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.A)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.A)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},r,{className:(0,u.A)("tabs__item",f.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 T(e){const t=h(e);return l.createElement("div",{className:(0,u.A)("tabs-container",f.tabList)},l.createElement(b,(0,n.A)({},e,t)),l.createElement(v,(0,n.A)({},e,t)))}function P(e){const t=(0,g.A)();return l.createElement(T,(0,n.A)({key:String(t)},e))}},28376:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>m,frontMatter:()=>i,metadata:()=>p,toc:()=>c});var n=a(58168),l=(a(96540),a(15680)),u=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},c=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:c},y="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/external-type-declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("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.yg)("p",null,"So instead of writing:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.yg)("p",null,"you will write:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8042],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),l=a(20053);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.A)(u.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>P});var n=a(58168),l=a(96540),u=a(20053),r=a(23104),i=a(56347),o=a(57485),p=a(31682),s=a(89466);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:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function d(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,p.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=d(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(!y({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]=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,u]=(0,s.Dv)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),g=(()=>{const e=o??c;return y({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),h(e)}),[p,h,u]),tabValues:u}}var g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),d=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(c(t),o(n))},y=e=>{let t=null;switch(e.key){case"Enter":d(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.A)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.A)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},r,{className:(0,u.A)("tabs__item",f.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 T(e){const t=h(e);return l.createElement("div",{className:(0,u.A)("tabs-container",f.tabList)},l.createElement(b,(0,n.A)({},e,t)),l.createElement(v,(0,n.A)({},e,t)))}function P(e){const t=(0,g.A)();return l.createElement(T,(0,n.A)({key:String(t)},e))}},28376:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>m,frontMatter:()=>i,metadata:()=>p,toc:()=>c});var n=a(58168),l=(a(96540),a(15680)),u=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},c=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:c},y="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/external-type-declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("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.yg)("p",null,"So instead of writing:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.yg)("p",null,"you will write:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/29cf2ad6.0007f100.js b/assets/js/29cf2ad6.e5258851.js similarity index 99% rename from assets/js/29cf2ad6.0007f100.js rename to assets/js/29cf2ad6.e5258851.js index 3576c9c34..790c18a65 100644 --- a/assets/js/29cf2ad6.0007f100.js +++ b/assets/js/29cf2ad6.e5258851.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2858],{6661:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>r,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>u,toc:()=>s});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},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}],g={toc:s},y="wrapper";function d(e){let{components:n,...t}=e;return(0,i.yg)(y,(0,a.A)({},g,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,i.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,i.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,i.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,i.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,i.yg)("p",null,"By settings ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,i.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,i.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,i.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,i.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,i.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,i.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,i.yg)("p",null,"The mutation below will log-in a user:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,i.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,i.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,i.yg)("p",null,"In Symfony, user objects implement ",(0,i.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,i.yg)("p",null,"If you want to get more fields, just add the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute to your user class:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"You can now query this field using an ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,i.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,i.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,i.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,i.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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")))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2858],{6661:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>r,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>u,toc:()=>s});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},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}],g={toc:s},y="wrapper";function d(e){let{components:n,...t}=e;return(0,i.yg)(y,(0,a.A)({},g,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,i.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,i.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,i.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,i.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,i.yg)("p",null,"By settings ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,i.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,i.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,i.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,i.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,i.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,i.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,i.yg)("p",null,"The mutation below will log-in a user:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,i.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,i.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,i.yg)("p",null,"In Symfony, user objects implement ",(0,i.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,i.yg)("p",null,"If you want to get more fields, just add the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute to your user class:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"You can now query this field using an ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,i.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,i.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,i.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,i.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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")))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/2b26025e.ffb0bc4a.js b/assets/js/2b26025e.b932bba2.js similarity index 97% rename from assets/js/2b26025e.ffb0bc4a.js rename to assets/js/2b26025e.b932bba2.js index f7bf53e21..e013e4d40 100644 --- a/assets/js/2b26025e.ffb0bc4a.js +++ b/assets/js/2b26025e.b932bba2.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9127],{9025:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>o,toc:()=>d});var n=a(58168),r=(a(96540),a(15680));a(67443);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/6.1/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/README.mdx",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/6.1/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.yg)(u,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("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([[9127],{9025:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>o,toc:()=>d});var n=a(58168),r=(a(96540),a(15680));a(67443);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/6.1/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/README.mdx",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/6.1/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.yg)(u,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("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.6351af1c.js b/assets/js/2bbfc5d5.fe37f321.js similarity index 99% rename from assets/js/2bbfc5d5.6351af1c.js rename to assets/js/2bbfc5d5.fe37f321.js index 59750cfa8..46984662e 100644 --- a/assets/js/2bbfc5d5.6351af1c.js +++ b/assets/js/2bbfc5d5.fe37f321.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[458],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),l=a(20053);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.A)(u.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>P});var n=a(58168),l=a(96540),u=a(20053),r=a(23104),o=a(56347),i=a(57485),p=a(31682),s=a(89466);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:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function d(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,p.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=d(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(!y({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]=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,u]=(0,s.Dv)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),g=(()=>{const e=i??c;return y({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{g&&o(g)}),[g]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),h(e)}),[p,h,u]),tabValues:u}}var g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:i,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),d=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==o&&(c(t),i(n))},y=e=>{let t=null;switch(e.key){case"Enter":d(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.A)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},r,{className:(0,u.A)("tabs__item",f.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 T(e){const t=h(e);return l.createElement("div",{className:(0,u.A)("tabs-container",f.tabList)},l.createElement(b,(0,n.A)({},e,t)),l.createElement(v,(0,n.A)({},e,t)))}function P(e){const t=(0,g.A)();return l.createElement(T,(0,n.A)({key:String(t)},e))}},35529:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var n=a(58168),l=(a(96540),a(15680)),u=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"multiple_output_types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"}},s={},c=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:c},y="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/3.0/external_type_declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("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.yg)("p",null,"So instead of writing:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.yg)("p",null,"you will write:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[458],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),l=a(20053);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.A)(u.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>P});var n=a(58168),l=a(96540),u=a(20053),r=a(23104),o=a(56347),i=a(57485),p=a(31682),s=a(89466);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:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function d(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,p.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=d(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(!y({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]=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,u]=(0,s.Dv)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),g=(()=>{const e=i??c;return y({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{g&&o(g)}),[g]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),h(e)}),[p,h,u]),tabValues:u}}var g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:i,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),d=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==o&&(c(t),i(n))},y=e=>{let t=null;switch(e.key){case"Enter":d(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.A)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},r,{className:(0,u.A)("tabs__item",f.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 T(e){const t=h(e);return l.createElement("div",{className:(0,u.A)("tabs-container",f.tabList)},l.createElement(b,(0,n.A)({},e,t)),l.createElement(v,(0,n.A)({},e,t)))}function P(e){const t=(0,g.A)();return l.createElement(T,(0,n.A)({key:String(t)},e))}},35529:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var n=a(58168),l=(a(96540),a(15680)),u=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"multiple_output_types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"}},s={},c=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:c},y="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/3.0/external_type_declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("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.yg)("p",null,"So instead of writing:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.yg)("p",null,"you will write:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/2d02c83c.a539b294.js b/assets/js/2d02c83c.1450cf33.js similarity index 98% rename from assets/js/2d02c83c.a539b294.js rename to assets/js/2d02c83c.1450cf33.js index e44e79934..8c2e294b9 100644 --- a/assets/js/2d02c83c.a539b294.js +++ b/assets/js/2d02c83c.1450cf33.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5e3],{60142:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(58168),a=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:t(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,n,t)=>{t.d(n,{A:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5e3],{60142:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(58168),a=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:t(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,n,t)=>{t.d(n,{A:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/2d4548df.dd5df81f.js b/assets/js/2d4548df.7b197969.js similarity index 99% rename from assets/js/2d4548df.dd5df81f.js rename to assets/js/2d4548df.7b197969.js index 5f5680898..7c6fd92f4 100644 --- a/assets/js/2d4548df.dd5df81f.js +++ b/assets/js/2d4548df.7b197969.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8478],{37942:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>d,toc:()=>s});var i=n(58168),a=(n(96540),n(15680));n(67443);const l={id:"field-middlewares",title:"Adding custom attributes with Field middlewares",sidebar_label:"Custom attributes"},r=void 0,d={unversionedId:"field-middlewares",id:"field-middlewares",title:"Adding custom attributes 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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom attributes with Field middlewares",sidebar_label:"Custom attributes"},sidebar:"docs",previous:{title:"Custom types",permalink:"/docs/next/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/next/argument-resolving"}},o={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Attributes parsing",id:"attributes-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:t,...l}=e;return(0,a.yg)(p,(0,i.A)({},u,l,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Logged]")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Right]")," attribute, you can develop your own attribute that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an attribute that targets a single argument (like ",(0,a.yg)("code",null,"#[AutoWire]"),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:n(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("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.yg)("h2",{id:"attributes-parsing"},"Attributes parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of attributes applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("inlineCode",{parentName:"p"},"#[OnlyDebug]")," attribute that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.yg)("p",null,"First, we have to define the attribute."),(0,a.yg)("pre",null,(0,a.yg)("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#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n")),(0,a.yg)("p",null,"Apart from being a classical attribute, this class implements the ",(0,a.yg)("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 attribute is to be used by middlewares.'),(0,a.yg)("p",null,"Now, we can write a middleware that will act upon this attribute."),(0,a.yg)("pre",null,(0,a.yg)("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 attribute 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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,t,n)=>{n.d(t,{A:()=>i});const i=n.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8478],{37942:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>d,toc:()=>s});var i=n(58168),a=(n(96540),n(15680));n(67443);const l={id:"field-middlewares",title:"Adding custom attributes with Field middlewares",sidebar_label:"Custom attributes"},r=void 0,d={unversionedId:"field-middlewares",id:"field-middlewares",title:"Adding custom attributes 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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom attributes with Field middlewares",sidebar_label:"Custom attributes"},sidebar:"docs",previous:{title:"Custom types",permalink:"/docs/next/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/next/argument-resolving"}},o={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Attributes parsing",id:"attributes-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:t,...l}=e;return(0,a.yg)(p,(0,i.A)({},u,l,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Logged]")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Right]")," attribute, you can develop your own attribute that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an attribute that targets a single argument (like ",(0,a.yg)("code",null,"#[AutoWire]"),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:n(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("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.yg)("h2",{id:"attributes-parsing"},"Attributes parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of attributes applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("inlineCode",{parentName:"p"},"#[OnlyDebug]")," attribute that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.yg)("p",null,"First, we have to define the attribute."),(0,a.yg)("pre",null,(0,a.yg)("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#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n")),(0,a.yg)("p",null,"Apart from being a classical attribute, this class implements the ",(0,a.yg)("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 attribute is to be used by middlewares.'),(0,a.yg)("p",null,"Now, we can write a middleware that will act upon this attribute."),(0,a.yg)("pre",null,(0,a.yg)("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 attribute 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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,t,n)=>{n.d(t,{A:()=>i});const i=n.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/2e25c87f.1ae4714b.js b/assets/js/2e25c87f.4ba0ae27.js similarity index 99% rename from assets/js/2e25c87f.1ae4714b.js rename to assets/js/2e25c87f.4ba0ae27.js index aa3d70141..db23e381c 100644 --- a/assets/js/2e25c87f.1ae4714b.js +++ b/assets/js/2e25c87f.4ba0ae27.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1345],{8608:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>d,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),l=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},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},g="wrapper";function d(e){let{components:n,...t}=e;return(0,l.yg)(g,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("div",{class:"alert alert--warning"},(0,l.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,l.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,l.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,l.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,l.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,l.yg)("p",null,"Now, go to the ",(0,l.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,l.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,l.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,l.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,l.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,l.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>d,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),l=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},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},g="wrapper";function d(e){let{components:n,...t}=e;return(0,l.yg)(g,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("div",{class:"alert alert--warning"},(0,l.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,l.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,l.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,l.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,l.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,l.yg)("p",null,"Now, go to the ",(0,l.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,l.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,l.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,l.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,l.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,l.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>o,toc:()=>g});var n=a(58168),l=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],y={toc:g},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.yg)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.yg)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("a",{parentName:"td",href:"/docs/4.3/external-type-declaration"},"the class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("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.yg)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/4.3/extend-type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"input-annotation"},"@Input annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true")," if name is not specified. Whether the annotated PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"update"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.yg)("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.yg)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.yg)("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.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"for"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string, array"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.3/input-types"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.yg)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"value"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("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.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9624],{50915:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>o,toc:()=>g});var n=a(58168),l=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],y={toc:g},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.yg)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.yg)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("a",{parentName:"td",href:"/docs/4.3/external-type-declaration"},"the class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("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.yg)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/4.3/extend-type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"input-annotation"},"@Input annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true")," if name is not specified. Whether the annotated PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"update"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.yg)("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.yg)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.yg)("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.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"for"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string, array"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.3/input-types"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.yg)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.3/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"value"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("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.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/2ef99682.c87f773f.js b/assets/js/2ef99682.63771824.js similarity index 99% rename from assets/js/2ef99682.c87f773f.js rename to assets/js/2ef99682.63771824.js index 3e19e155b..96113f887 100644 --- a/assets/js/2ef99682.c87f773f.js +++ b/assets/js/2ef99682.63771824.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9092],{27486:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>u,contentTitle:()=>s,default:()=>d,frontMatter:()=>o,metadata:()=>i,toc:()=>l});var n=a(58168),p=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:t,...a}=e;return(0,p.yg)(y,(0,n.A)({},r,a,{components:t,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.yg)("p",null,"GraphQL comes with an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID!")\n */\n')),(0,p.yg)("h2",{id:"usage"},"Usage"),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.yg)("p",null,"You can use the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Query")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Field")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@SourceField"))),(0,p.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.yg)("p",null,"In order to create a custom output type, you need to:"),(0,p.yg)("ol",null,(0,p.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,p.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.yg)("p",null,"You'll find more details on the ",(0,p.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,p.yg)("hr",null),(0,p.yg)("p",null,"In order to find existing types, the schema is using ",(0,p.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,p.yg)("p",null,"Any class extending ",(0,p.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.yg)("p",null,"The easiest way is to use a ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.yg)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9092],{27486:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>u,contentTitle:()=>s,default:()=>d,frontMatter:()=>o,metadata:()=>i,toc:()=>l});var n=a(58168),p=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:t,...a}=e;return(0,p.yg)(y,(0,n.A)({},r,a,{components:t,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.yg)("p",null,"GraphQL comes with an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID!")\n */\n')),(0,p.yg)("h2",{id:"usage"},"Usage"),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.yg)("p",null,"You can use the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Query")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Field")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@SourceField"))),(0,p.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.yg)("p",null,"In order to create a custom output type, you need to:"),(0,p.yg)("ol",null,(0,p.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,p.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.yg)("p",null,"You'll find more details on the ",(0,p.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,p.yg)("hr",null),(0,p.yg)("p",null,"In order to find existing types, the schema is using ",(0,p.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,p.yg)("p",null,"Any class extending ",(0,p.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.yg)("p",null,"The easiest way is to use a ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.yg)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/2f36012a.47f01b7f.js b/assets/js/2f36012a.9ea7bba6.js similarity index 98% rename from assets/js/2f36012a.47f01b7f.js rename to assets/js/2f36012a.9ea7bba6.js index 11a5f88d1..dd9907ef6 100644 --- a/assets/js/2f36012a.47f01b7f.js +++ b/assets/js/2f36012a.9ea7bba6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1674],{52095:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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([[1674],{52095:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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/2f46a9d9.fbab3a9d.js b/assets/js/2f46a9d9.195005ee.js similarity index 99% rename from assets/js/2f46a9d9.fbab3a9d.js rename to assets/js/2f46a9d9.195005ee.js index 70489b7c3..00790fa00 100644 --- a/assets/js/2f46a9d9.fbab3a9d.js +++ b/assets/js/2f46a9d9.195005ee.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4706],{10154:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>y,frontMatter:()=>r,metadata:()=>l,toc:()=>u});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"input-types",title:"Input types",sidebar_label:"Input types"},o=void 0,l={unversionedId:"input-types",id:"version-8.0.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-8.0.0/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-8.0.0/input-types.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},p={},u=[{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}],s={toc:u},d="wrapper";function y(e){let{components:t,...n}=e;return(0,i.yg)(d,(0,a.A)({},s,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,i.yg)("p",null,"Your GraphQL query might look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,i.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,i.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,i.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,i.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,i.yg)("a",{parentName:"p",href:"#input-attribute"},(0,i.yg)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,i.yg)("a",{parentName:"p",href:"#factory"},"Factory method"),"."),(0,i.yg)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,i.yg)("p",null,"Using the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Now if you call the ",(0,i.yg)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,i.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,i.yg)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,i.yg)("p",null,"There are some important things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," attribute is recognized on properties for Input Type, as well as setters."),(0,i.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,i.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,i.yg)("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,i.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," attribute on the setter, instead of the property, allowing you to have use many other attributes (",(0,i.yg)("inlineCode",{parentName:"li"},"Security"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,i.yg)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,i.yg)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,i.yg)("li",{parentName:"ul"},"It's advised to use the ",(0,i.yg)("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,i.yg)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,i.yg)("p",null,"Simple usage of the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]"),' attribute 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,i.yg)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," class."),(0,i.yg)("p",null,"You can add multiple ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]")," attributed to the same class, give them different names and link different fields.\nConsider the following example:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"There are 2 input types added to the ",(0,i.yg)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,i.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,i.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,i.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,i.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,i.yg)("p",null,"Note that ",(0,i.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,i.yg)("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,i.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,i.yg)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,i.yg)("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,i.yg)("h2",{id:"factory"},"Factory"),(0,i.yg)("p",null,"A ",(0,i.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,i.yg)("p",null,"Here is an example of factory:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory attribute 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,i.yg)("p",null,"and now, you can run query like this:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,i.yg)("strong",{parentName:"li"},"#","[Factory]")," attribute."),(0,i.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,i.yg)("p",null,"A few important things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,i.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,i.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,i.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the #',"[Factory]"," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n")),(0,i.yg)("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,i.yg)("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,i.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[UseInputType]")," attribute to force an input type of a parameter."),(0,i.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,i.yg)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,i.yg)("inlineCode",{parentName:"p"},"#[UseInputType]")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Factory]")," attribute to achieve your goal."),(0,i.yg)("p",null,"Here is an annotated sample:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("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,i.yg)("p",null,"Image your ",(0,i.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,i.yg)("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,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"With the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[HideParameter]")," attribute, you can choose to remove from the GraphQL schema any argument."),(0,i.yg)("p",null,"To be able to hide an argument, the argument must have a default value."))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4706],{10154:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>y,frontMatter:()=>r,metadata:()=>l,toc:()=>u});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"input-types",title:"Input types",sidebar_label:"Input types"},o=void 0,l={unversionedId:"input-types",id:"version-8.0.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-8.0.0/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-8.0.0/input-types.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},p={},u=[{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}],s={toc:u},d="wrapper";function y(e){let{components:t,...n}=e;return(0,i.yg)(d,(0,a.A)({},s,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,i.yg)("p",null,"Your GraphQL query might look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,i.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,i.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,i.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,i.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,i.yg)("a",{parentName:"p",href:"#input-attribute"},(0,i.yg)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,i.yg)("a",{parentName:"p",href:"#factory"},"Factory method"),"."),(0,i.yg)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,i.yg)("p",null,"Using the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Now if you call the ",(0,i.yg)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,i.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,i.yg)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,i.yg)("p",null,"There are some important things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," attribute is recognized on properties for Input Type, as well as setters."),(0,i.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,i.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,i.yg)("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,i.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," attribute on the setter, instead of the property, allowing you to have use many other attributes (",(0,i.yg)("inlineCode",{parentName:"li"},"Security"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,i.yg)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,i.yg)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,i.yg)("li",{parentName:"ul"},"It's advised to use the ",(0,i.yg)("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,i.yg)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,i.yg)("p",null,"Simple usage of the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]"),' attribute 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,i.yg)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," class."),(0,i.yg)("p",null,"You can add multiple ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]")," attributed to the same class, give them different names and link different fields.\nConsider the following example:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"There are 2 input types added to the ",(0,i.yg)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,i.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,i.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,i.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,i.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,i.yg)("p",null,"Note that ",(0,i.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,i.yg)("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,i.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,i.yg)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,i.yg)("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,i.yg)("h2",{id:"factory"},"Factory"),(0,i.yg)("p",null,"A ",(0,i.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,i.yg)("p",null,"Here is an example of factory:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory attribute 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,i.yg)("p",null,"and now, you can run query like this:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,i.yg)("strong",{parentName:"li"},"#","[Factory]")," attribute."),(0,i.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,i.yg)("p",null,"A few important things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,i.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,i.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,i.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the #',"[Factory]"," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n")),(0,i.yg)("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,i.yg)("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,i.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[UseInputType]")," attribute to force an input type of a parameter."),(0,i.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,i.yg)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,i.yg)("inlineCode",{parentName:"p"},"#[UseInputType]")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Factory]")," attribute to achieve your goal."),(0,i.yg)("p",null,"Here is an annotated sample:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("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,i.yg)("p",null,"Image your ",(0,i.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,i.yg)("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,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"With the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[HideParameter]")," attribute, you can choose to remove from the GraphQL schema any argument."),(0,i.yg)("p",null,"To be able to hide an argument, the argument must have a default value."))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/2fc68ddc.8512b0e9.js b/assets/js/2fc68ddc.2591b067.js similarity index 98% rename from assets/js/2fc68ddc.8512b0e9.js rename to assets/js/2fc68ddc.2591b067.js index 4c1fc1994..535417103 100644 --- a/assets/js/2fc68ddc.8512b0e9.js +++ b/assets/js/2fc68ddc.2591b067.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1763],{70910:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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-8.0.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-8.0.0/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-8.0.0/universal-service-providers.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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([[1763],{70910:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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-8.0.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-8.0.0/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-8.0.0/universal-service-providers.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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/30940d42.2f77f2a1.js b/assets/js/30940d42.f7fab1ba.js similarity index 99% rename from assets/js/30940d42.2f77f2a1.js rename to assets/js/30940d42.f7fab1ba.js index 9ed652c8c..4ec64a052 100644 --- a/assets/js/30940d42.2f77f2a1.js +++ b/assets/js/30940d42.f7fab1ba.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7483],{5259:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,i.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Now, go to the ",(0,i.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,i.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,i.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Now, go to the ",(0,i.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,i.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],g={toc:l},c="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},g,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/universal_service_providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6972],{24664:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],g={toc:l},c="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},g,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/universal_service_providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/323a980a.0fa1a14b.js b/assets/js/323a980a.c8a6a4d4.js similarity index 98% rename from assets/js/323a980a.0fa1a14b.js rename to assets/js/323a980a.c8a6a4d4.js index 5ca5ed2fa..1325b7379 100644 --- a/assets/js/323a980a.0fa1a14b.js +++ b/assets/js/323a980a.c8a6a4d4.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5362],{19840:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>d,frontMatter:()=>r,metadata:()=>a,toc:()=>c});var o=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"subscriptions",title:"Subscriptions",sidebar_label:"Subscriptions"},s=void 0,a={unversionedId:"subscriptions",id:"subscriptions",title:"Subscriptions",description:"In GraphQLite, subscriptions are created like queries or mutations.",source:"@site/docs/subscriptions.mdx",sourceDirName:".",slug:"/subscriptions",permalink:"/docs/next/subscriptions",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/subscriptions.mdx",tags:[],version:"current",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"subscriptions",title:"Subscriptions",sidebar_label:"Subscriptions"},sidebar:"docs",previous:{title:"Mutations",permalink:"/docs/next/mutations"},next:{title:"Type mapping",permalink:"/docs/next/type-mapping"}},p={},c=[],l={toc:c},u="wrapper";function d(e){let{components:t,...n}=e;return(0,i.yg)(u,(0,o.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, subscriptions are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/queries"},"like queries")," or ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/mutations"},"mutations"),"."),(0,i.yg)("p",null,"To create a subscription, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Subscription(outputType: 'Product')]\n public function productAdded(?ID $categoryId = null): void\n {\n // Some code that sets up any connections, stores the subscription details, etc.\n }\n}\n")),(0,i.yg)("p",null,"As you will notice in the above example, we're returning ",(0,i.yg)("inlineCode",{parentName:"p"},"void"),". In general, this is probably the\ncorrect return type."),(0,i.yg)("p",null,"You could, however, type the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," as the return type of the method, instead\nof using the ",(0,i.yg)("inlineCode",{parentName:"p"},"outputType")," argument on the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute. This means you\nwould have to return an instance of ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," from the method though. One exception here, is if\nyou intend to use PHP for your long-running streaming process, you could block the process inside\nthe controller and basically never return anything from the method, just terminating the\nconnection/stream when it breaks, or when the client disconnects."),(0,i.yg)("p",null,"Most implementations will want to offload the actual real-time streaming connection to a better suited\ntechnology, like SSE (server-sent events), WebSockets, etc. GraphQLite does not make any assumptions\nhere. Therefore, it's most practical to return ",(0,i.yg)("inlineCode",{parentName:"p"},"void")," from the controller method. Since GraphQL\nis a strictly typed spec, we cannot return anything other than the defined ",(0,i.yg)("inlineCode",{parentName:"p"},"outputType")," from the request.\nThat would be a violation of the GraphQL specification. Returning ",(0,i.yg)("inlineCode",{parentName:"p"},"void"),", which is translated to ",(0,i.yg)("inlineCode",{parentName:"p"},"null"),"\nin the GraphQL response body, allows for us to complete the request and terminate the PHP process."),(0,i.yg)("p",null,"We recommend using response headers to pass back any necessary information realted to the subscription.\nThis might be a subscription ID, a streaming server URL to connect to, or whatever you need to pass\nback to the client."),(0,i.yg)("div",{class:"alert alert--info"},"In the future, it may make sense to implement streaming servers directly into GraphQLite, especially as PHP progresses with async and parallel processing. At this time, we might consider returning a `Generator` (or `Fiber`) from the controller method."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5362],{19840:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>d,frontMatter:()=>r,metadata:()=>a,toc:()=>c});var o=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"subscriptions",title:"Subscriptions",sidebar_label:"Subscriptions"},s=void 0,a={unversionedId:"subscriptions",id:"subscriptions",title:"Subscriptions",description:"In GraphQLite, subscriptions are created like queries or mutations.",source:"@site/docs/subscriptions.mdx",sourceDirName:".",slug:"/subscriptions",permalink:"/docs/next/subscriptions",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/subscriptions.mdx",tags:[],version:"current",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"subscriptions",title:"Subscriptions",sidebar_label:"Subscriptions"},sidebar:"docs",previous:{title:"Mutations",permalink:"/docs/next/mutations"},next:{title:"Type mapping",permalink:"/docs/next/type-mapping"}},p={},c=[],l={toc:c},u="wrapper";function d(e){let{components:t,...n}=e;return(0,i.yg)(u,(0,o.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, subscriptions are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/queries"},"like queries")," or ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/mutations"},"mutations"),"."),(0,i.yg)("p",null,"To create a subscription, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Subscription(outputType: 'Product')]\n public function productAdded(?ID $categoryId = null): void\n {\n // Some code that sets up any connections, stores the subscription details, etc.\n }\n}\n")),(0,i.yg)("p",null,"As you will notice in the above example, we're returning ",(0,i.yg)("inlineCode",{parentName:"p"},"void"),". In general, this is probably the\ncorrect return type."),(0,i.yg)("p",null,"You could, however, type the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," as the return type of the method, instead\nof using the ",(0,i.yg)("inlineCode",{parentName:"p"},"outputType")," argument on the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute. This means you\nwould have to return an instance of ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," from the method though. One exception here, is if\nyou intend to use PHP for your long-running streaming process, you could block the process inside\nthe controller and basically never return anything from the method, just terminating the\nconnection/stream when it breaks, or when the client disconnects."),(0,i.yg)("p",null,"Most implementations will want to offload the actual real-time streaming connection to a better suited\ntechnology, like SSE (server-sent events), WebSockets, etc. GraphQLite does not make any assumptions\nhere. Therefore, it's most practical to return ",(0,i.yg)("inlineCode",{parentName:"p"},"void")," from the controller method. Since GraphQL\nis a strictly typed spec, we cannot return anything other than the defined ",(0,i.yg)("inlineCode",{parentName:"p"},"outputType")," from the request.\nThat would be a violation of the GraphQL specification. Returning ",(0,i.yg)("inlineCode",{parentName:"p"},"void"),", which is translated to ",(0,i.yg)("inlineCode",{parentName:"p"},"null"),"\nin the GraphQL response body, allows for us to complete the request and terminate the PHP process."),(0,i.yg)("p",null,"We recommend using response headers to pass back any necessary information realted to the subscription.\nThis might be a subscription ID, a streaming server URL to connect to, or whatever you need to pass\nback to the client."),(0,i.yg)("div",{class:"alert alert--info"},"In the future, it may make sense to implement streaming servers directly into GraphQLite, especially as PHP progresses with async and parallel processing. At this time, we might consider returning a `Generator` (or `Fiber`) from the controller method."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/32e2b5e3.e118ef3e.js b/assets/js/32e2b5e3.89351c93.js similarity index 99% rename from assets/js/32e2b5e3.e118ef3e.js rename to assets/js/32e2b5e3.89351c93.js index 0a389a8df..dbd2c74f4 100644 --- a/assets/js/32e2b5e3.e118ef3e.js +++ b/assets/js/32e2b5e3.89351c93.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5730],{39985:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>r,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>u,toc:()=>s});var a=t(58168),i=(t(96540),t(15680));t(67443);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-8.0.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-8.0.0/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-8.0.0/symfony-bundle-advanced.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},y="wrapper";function d(e){let{components:n,...t}=e;return(0,i.yg)(y,(0,a.A)({},g,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,i.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,i.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,i.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,i.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,i.yg)("p",null,"By settings ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,i.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,i.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,i.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,i.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,i.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,i.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,i.yg)("p",null,"The mutation below will log-in a user:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,i.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,i.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,i.yg)("p",null,"In Symfony, user objects implement ",(0,i.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,i.yg)("p",null,"If you want to get more fields, just add the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute to your user class:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"You can now query this field using an ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,i.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,i.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,i.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,i.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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")))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5730],{39985:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>r,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>u,toc:()=>s});var a=t(58168),i=(t(96540),t(15680));t(67443);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-8.0.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-8.0.0/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-8.0.0/symfony-bundle-advanced.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},y="wrapper";function d(e){let{components:n,...t}=e;return(0,i.yg)(y,(0,a.A)({},g,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,i.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,i.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,i.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,i.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,i.yg)("p",null,"By settings ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,i.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,i.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,i.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,i.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,i.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,i.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,i.yg)("p",null,"The mutation below will log-in a user:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,i.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,i.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,i.yg)("p",null,"In Symfony, user objects implement ",(0,i.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,i.yg)("p",null,"If you want to get more fields, just add the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute to your user class:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"You can now query this field using an ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,i.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,i.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,i.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,i.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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")))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/332827b4.252983b3.js b/assets/js/332827b4.8809e5b5.js similarity index 98% rename from assets/js/332827b4.252983b3.js rename to assets/js/332827b4.8809e5b5.js index cbbcb53a1..585afa73e 100644 --- a/assets/js/332827b4.252983b3.js +++ b/assets/js/332827b4.8809e5b5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4780],{14335:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>d,frontMatter:()=>r,metadata:()=>a,toc:()=>c});var o=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"subscriptions",title:"Subscriptions",sidebar_label:"Subscriptions"},s=void 0,a={unversionedId:"subscriptions",id:"version-7.0.0/subscriptions",title:"Subscriptions",description:"In GraphQLite, subscriptions are created like queries or mutations.",source:"@site/versioned_docs/version-7.0.0/subscriptions.mdx",sourceDirName:".",slug:"/subscriptions",permalink:"/docs/7.0.0/subscriptions",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/subscriptions.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"subscriptions",title:"Subscriptions",sidebar_label:"Subscriptions"},sidebar:"docs",previous:{title:"Mutations",permalink:"/docs/7.0.0/mutations"},next:{title:"Type mapping",permalink:"/docs/7.0.0/type-mapping"}},p={},c=[],l={toc:c},u="wrapper";function d(e){let{components:t,...n}=e;return(0,i.yg)(u,(0,o.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, subscriptions are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/7.0.0/queries"},"like queries")," or ",(0,i.yg)("a",{parentName:"p",href:"/docs/7.0.0/mutations"},"mutations"),"."),(0,i.yg)("p",null,"To create a subscription, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Subscription(outputType: 'Product')]\n public function productAdded(?ID $categoryId = null): void\n {\n // Some code that sets up any connections, stores the subscription details, etc.\n }\n}\n")),(0,i.yg)("p",null,"As you will notice in the above example, we're returning ",(0,i.yg)("inlineCode",{parentName:"p"},"void"),". In general, this is probably the\ncorrect return type."),(0,i.yg)("p",null,"You could, however, type the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," as the return type of the method, instead\nof using the ",(0,i.yg)("inlineCode",{parentName:"p"},"outputType")," argument on the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute. This means you\nwould have to return an instance of ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," from the method though. One exception here, is if\nyou intend to use PHP for your long-running streaming process, you could block the process inside\nthe controller and basically never return anything from the method, just terminating the\nconnection/stream when it breaks, or when the client disconnects."),(0,i.yg)("p",null,"Most implementations will want to offload the actual real-time streaming connection to a better suited\ntechnology, like SSE (server-sent events), WebSockets, etc. GraphQLite does not make any assumptions\nhere. Therefore, it's most practical to return ",(0,i.yg)("inlineCode",{parentName:"p"},"void")," from the controller method. Since GraphQL\nis a strictly typed spec, we cannot return anything other than the defined ",(0,i.yg)("inlineCode",{parentName:"p"},"outputType")," from the request.\nThat would be a violation of the GraphQL specification. Returning ",(0,i.yg)("inlineCode",{parentName:"p"},"void"),", which is translated to ",(0,i.yg)("inlineCode",{parentName:"p"},"null"),"\nin the GraphQL response body, allows for us to complete the request and terminate the PHP process."),(0,i.yg)("p",null,"We recommend using response headers to pass back any necessary information realted to the subscription.\nThis might be a subscription ID, a streaming server URL to connect to, or whatever you need to pass\nback to the client."),(0,i.yg)("div",{class:"alert alert--info"},"In the future, it may make sense to implement streaming servers directly into GraphQLite, especially as PHP progresses with async and parallel processing. At this time, we might consider returning a `Generator` (or `Fiber`) from the controller method."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4780],{14335:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>d,frontMatter:()=>r,metadata:()=>a,toc:()=>c});var o=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"subscriptions",title:"Subscriptions",sidebar_label:"Subscriptions"},s=void 0,a={unversionedId:"subscriptions",id:"version-7.0.0/subscriptions",title:"Subscriptions",description:"In GraphQLite, subscriptions are created like queries or mutations.",source:"@site/versioned_docs/version-7.0.0/subscriptions.mdx",sourceDirName:".",slug:"/subscriptions",permalink:"/docs/7.0.0/subscriptions",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/subscriptions.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"subscriptions",title:"Subscriptions",sidebar_label:"Subscriptions"},sidebar:"docs",previous:{title:"Mutations",permalink:"/docs/7.0.0/mutations"},next:{title:"Type mapping",permalink:"/docs/7.0.0/type-mapping"}},p={},c=[],l={toc:c},u="wrapper";function d(e){let{components:t,...n}=e;return(0,i.yg)(u,(0,o.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, subscriptions are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/7.0.0/queries"},"like queries")," or ",(0,i.yg)("a",{parentName:"p",href:"/docs/7.0.0/mutations"},"mutations"),"."),(0,i.yg)("p",null,"To create a subscription, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Subscription(outputType: 'Product')]\n public function productAdded(?ID $categoryId = null): void\n {\n // Some code that sets up any connections, stores the subscription details, etc.\n }\n}\n")),(0,i.yg)("p",null,"As you will notice in the above example, we're returning ",(0,i.yg)("inlineCode",{parentName:"p"},"void"),". In general, this is probably the\ncorrect return type."),(0,i.yg)("p",null,"You could, however, type the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," as the return type of the method, instead\nof using the ",(0,i.yg)("inlineCode",{parentName:"p"},"outputType")," argument on the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute. This means you\nwould have to return an instance of ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," from the method though. One exception here, is if\nyou intend to use PHP for your long-running streaming process, you could block the process inside\nthe controller and basically never return anything from the method, just terminating the\nconnection/stream when it breaks, or when the client disconnects."),(0,i.yg)("p",null,"Most implementations will want to offload the actual real-time streaming connection to a better suited\ntechnology, like SSE (server-sent events), WebSockets, etc. GraphQLite does not make any assumptions\nhere. Therefore, it's most practical to return ",(0,i.yg)("inlineCode",{parentName:"p"},"void")," from the controller method. Since GraphQL\nis a strictly typed spec, we cannot return anything other than the defined ",(0,i.yg)("inlineCode",{parentName:"p"},"outputType")," from the request.\nThat would be a violation of the GraphQL specification. Returning ",(0,i.yg)("inlineCode",{parentName:"p"},"void"),", which is translated to ",(0,i.yg)("inlineCode",{parentName:"p"},"null"),"\nin the GraphQL response body, allows for us to complete the request and terminate the PHP process."),(0,i.yg)("p",null,"We recommend using response headers to pass back any necessary information realted to the subscription.\nThis might be a subscription ID, a streaming server URL to connect to, or whatever you need to pass\nback to the client."),(0,i.yg)("div",{class:"alert alert--info"},"In the future, it may make sense to implement streaming servers directly into GraphQLite, especially as PHP progresses with async and parallel processing. At this time, we might consider returning a `Generator` (or `Fiber`) from the controller method."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/346bcb92.7616f868.js b/assets/js/346bcb92.6c319671.js similarity index 99% rename from assets/js/346bcb92.7616f868.js rename to assets/js/346bcb92.6c319671.js index bb1b11cd5..424a1f4bd 100644 --- a/assets/js/346bcb92.7616f868.js +++ b/assets/js/346bcb92.6c319671.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8548],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),s=a(56347),i=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),h(e)}),[u,h,l]),tabValues:l}}var f=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},g=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},o,{className:(0,l.A)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":s===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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},2417:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(g,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"You will need to install the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"In your query, simply return a class that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.yg)("p",null,'The "count" field returns the ',(0,r.yg)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8548],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),s=a(56347),i=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),h(e)}),[u,h,l]),tabValues:l}}var f=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},g=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},o,{className:(0,l.A)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":s===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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},2417:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(g,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"You will need to install the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"In your query, simply return a class that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.yg)("p",null,'The "count" field returns the ',(0,r.yg)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/354a9b78.e5046e45.js b/assets/js/354a9b78.e630317e.js similarity index 98% rename from assets/js/354a9b78.e5046e45.js rename to assets/js/354a9b78.e630317e.js index 821863730..a85675531 100644 --- a/assets/js/354a9b78.e5046e45.js +++ b/assets/js/354a9b78.e630317e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7942],{952:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],y={toc:d},s="wrapper";function u(e){let{components:t,...n}=e;return(0,i.yg)(s,(0,a.A)({},y,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,i.yg)("code",null,"@Factory")," tag, ",(0,i.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,i.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,i.yg)("p",null,"Just like with output type (that can be ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/extend_type"},"extended using the ",(0,i.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,i.yg)("div",{class:"alert alert--info"},"The ",(0,i.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,i.yg)("code",null,"@Factory")," method. This can happen if the ",(0,i.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,i.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,i.yg)("p",null,"Let's assume you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Assuming you ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,i.yg)("p",null,"A few things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,i.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,i.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7942],{952:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],y={toc:d},s="wrapper";function u(e){let{components:t,...n}=e;return(0,i.yg)(s,(0,a.A)({},y,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,i.yg)("code",null,"@Factory")," tag, ",(0,i.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,i.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,i.yg)("p",null,"Just like with output type (that can be ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/extend_type"},"extended using the ",(0,i.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,i.yg)("div",{class:"alert alert--info"},"The ",(0,i.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,i.yg)("code",null,"@Factory")," method. This can happen if the ",(0,i.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,i.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,i.yg)("p",null,"Let's assume you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Assuming you ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,i.yg)("p",null,"A few things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,i.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,i.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/366cfce3.76971fab.js b/assets/js/366cfce3.e6f66bfb.js similarity index 99% rename from assets/js/366cfce3.76971fab.js rename to assets/js/366cfce3.e6f66bfb.js index 9fffffa6e..bca209f6b 100644 --- a/assets/js/366cfce3.76971fab.js +++ b/assets/js/366cfce3.e6f66bfb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5180],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),i=n(56347),s=n(57485),u=n(31682),p=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.W6)(),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.aZ)(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),[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]=y({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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),m=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);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 m=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":i===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 T(e){const t=g(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},3190:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 y(e){let{components:t,...i}=e;return(0,r.yg)(h,(0,a.A)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.yg)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.yg)("p",null,"Read the ",(0,r.yg)("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.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:n(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}y.isMDXComponent=!0},67258:(e,t,n)=>{n.d(t,{A:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5180],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),i=n(56347),s=n(57485),u=n(31682),p=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.W6)(),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.aZ)(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),[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]=y({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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),m=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);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 m=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":i===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 T(e){const t=g(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},3190:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 y(e){let{components:t,...i}=e;return(0,r.yg)(h,(0,a.A)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.yg)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.yg)("p",null,"Read the ",(0,r.yg)("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.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:n(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}y.isMDXComponent=!0},67258:(e,t,n)=>{n.d(t,{A:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/36b1b0cc.0cb2f4db.js b/assets/js/36b1b0cc.60fff3a5.js similarity index 99% rename from assets/js/36b1b0cc.0cb2f4db.js rename to assets/js/36b1b0cc.60fff3a5.js index e3028e7f2..803ef0a0b 100644 --- a/assets/js/36b1b0cc.0cb2f4db.js +++ b/assets/js/36b1b0cc.60fff3a5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9219],{59239:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>s,contentTitle:()=>l,default:()=>d,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var n=t(58168),i=(t(96540),t(15680));t(67443);const r={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},l=void 0,o={unversionedId:"laravel-package-advanced",id:"version-8.0.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-8.0.0/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-8.0.0/laravel-package-advanced.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},p=[{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}],u={toc:p},g="wrapper";function d(e){let{components:a,...t}=e;return(0,i.yg)(g,(0,n.A)({},u,t,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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,i.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,i.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,i.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,i.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Validate]")," attribute to use Laravel validation rules in your\ninput types."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Validate]")," attribute in any query / mutation / field / factory / decorator."),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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 }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password"\n }\n }\n ]\n}\n')),(0,i.yg)("p",null,"You can use any validation rule described in ",(0,i.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,i.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,i.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,i.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Notice that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,i.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,i.yg)("li",{parentName:"ul"},"you MUST add a ",(0,i.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,i.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,i.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,i.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,i.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,i.yg)("p",null,"Note: if you are using ",(0,i.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,i.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,i.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,i.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,i.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,i.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute on each getter."),(0,i.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[MagicField]")," attribute to help you\nworking with magic properties."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,i.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute on the ",(0,i.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,i.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,i.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,i.yg)("p",null,"In short:"),(0,i.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n\n #[Field]\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,i.yg)("div",{class:"alert alert--success"},"This works:",(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[MagicField(name: "phone", phpType:"App\\\\Phone")]\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))),(0,i.yg)("h2",{id:"export-the-schema-from-the-cli"},"Export the schema from the CLI"),(0,i.yg)("p",null,"The extension comes with a special command: ",(0,i.yg)("inlineCode",{parentName:"p"},"graphqlite:export-schema"),"."),(0,i.yg)("p",null,"Usage:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ ./artisan graphqlite:export-schema --output=schema.graphql\n")),(0,i.yg)("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)."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9219],{59239:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>s,contentTitle:()=>l,default:()=>d,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var n=t(58168),i=(t(96540),t(15680));t(67443);const r={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},l=void 0,o={unversionedId:"laravel-package-advanced",id:"version-8.0.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-8.0.0/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-8.0.0/laravel-package-advanced.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},p=[{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}],u={toc:p},g="wrapper";function d(e){let{components:a,...t}=e;return(0,i.yg)(g,(0,n.A)({},u,t,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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,i.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,i.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,i.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,i.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Validate]")," attribute to use Laravel validation rules in your\ninput types."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Validate]")," attribute in any query / mutation / field / factory / decorator."),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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 }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password"\n }\n }\n ]\n}\n')),(0,i.yg)("p",null,"You can use any validation rule described in ",(0,i.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,i.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,i.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,i.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Notice that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,i.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,i.yg)("li",{parentName:"ul"},"you MUST add a ",(0,i.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,i.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,i.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,i.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,i.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,i.yg)("p",null,"Note: if you are using ",(0,i.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,i.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,i.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,i.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,i.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,i.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute on each getter."),(0,i.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[MagicField]")," attribute to help you\nworking with magic properties."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,i.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute on the ",(0,i.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,i.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,i.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,i.yg)("p",null,"In short:"),(0,i.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n\n #[Field]\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,i.yg)("div",{class:"alert alert--success"},"This works:",(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[MagicField(name: "phone", phpType:"App\\\\Phone")]\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))),(0,i.yg)("h2",{id:"export-the-schema-from-the-cli"},"Export the schema from the CLI"),(0,i.yg)("p",null,"The extension comes with a special command: ",(0,i.yg)("inlineCode",{parentName:"p"},"graphqlite:export-schema"),"."),(0,i.yg)("p",null,"Usage:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ ./artisan graphqlite:export-schema --output=schema.graphql\n")),(0,i.yg)("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)."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/36ddade1.eea21b14.js b/assets/js/36ddade1.f83468ca.js similarity index 97% rename from assets/js/36ddade1.eea21b14.js rename to assets/js/36ddade1.f83468ca.js index 4f4f9b0d8..40c97e683 100644 --- a/assets/js/36ddade1.eea21b14.js +++ b/assets/js/36ddade1.f83468ca.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2917],{73630:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:l},g="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,r.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2917],{73630:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:l},g="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,r.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.0/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/379bfe51.dc9f16bf.js b/assets/js/379bfe51.b4685fa8.js similarity index 99% rename from assets/js/379bfe51.dc9f16bf.js rename to assets/js/379bfe51.b4685fa8.js index 957bcdd7c..97d26949b 100644 --- a/assets/js/379bfe51.dc9f16bf.js +++ b/assets/js/379bfe51.b4685fa8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8313],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),i=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??p;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&i(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),h(e)}),[u,h,l]),tabValues:l}}var f=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==i&&(p(t),s(n))},g=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},o,{className:(0,l.A)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":i===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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},27685:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(g,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"You will need to install the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"In your query, simply return a class that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.yg)("p",null,'The "count" field returns the ',(0,r.yg)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8313],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),i=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=s??p;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&i(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),h(e)}),[u,h,l]),tabValues:l}}var f=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==i&&(p(t),s(n))},g=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},o,{className:(0,l.A)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":i===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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},27685:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>i,metadata:()=>u,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(g,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"You will need to install the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"In your query, simply return a class that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.yg)("p",null,'The "count" field returns the ',(0,r.yg)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/380575ae.fa09855a.js b/assets/js/380575ae.5662be3c.js similarity index 99% rename from assets/js/380575ae.fa09855a.js rename to assets/js/380575ae.5662be3c.js index 5d30851b6..e9b6bd64c 100644 --- a/assets/js/380575ae.fa09855a.js +++ b/assets/js/380575ae.5662be3c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7757],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),s=a(56347),i=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),h(e)}),[u,h,l]),tabValues:l}}var f=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},g=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},o,{className:(0,l.A)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":s===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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},28669:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);const s={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},i=void 0,u={unversionedId:"pagination",id:"version-7.0.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-7.0.0/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/7.0.0/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/pagination.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"docs",previous:{title:"File uploads",permalink:"/docs/7.0.0/file-uploads"},next:{title:"Custom types",permalink:"/docs/7.0.0/custom-types"}},c={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],d={toc:p},g="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(g,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"You will need to install the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"In your query, simply return a class that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.yg)("p",null,'The "count" field returns the ',(0,r.yg)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7757],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),s=a(56347),i=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),h(e)}),[u,h,l]),tabValues:l}}var f=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},g=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},o,{className:(0,l.A)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":s===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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},28669:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);const s={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},i=void 0,u={unversionedId:"pagination",id:"version-7.0.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-7.0.0/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/7.0.0/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/pagination.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"docs",previous:{title:"File uploads",permalink:"/docs/7.0.0/file-uploads"},next:{title:"Custom types",permalink:"/docs/7.0.0/custom-types"}},c={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],d={toc:p},g="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(g,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"You will need to install the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"In your query, simply return a class that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.yg)("p",null,'The "count" field returns the ',(0,r.yg)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/38317547.3402cbae.js b/assets/js/38317547.9620f8ef.js similarity index 98% rename from assets/js/38317547.3402cbae.js rename to assets/js/38317547.9620f8ef.js index 7f05ba9fd..4bec2bb28 100644 --- a/assets/js/38317547.3402cbae.js +++ b/assets/js/38317547.9620f8ef.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4225],{99983:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>r,metadata:()=>l,toc:()=>o});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.yg)("p",null,"Written in ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.yg)("p",null,"The GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.yg)("div",{class:"alert alert--warning"},"Right now, there is no way to explicitly declare a GraphQL interface using GraphQLite.",(0,i.yg)("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([[4225],{99983:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>r,metadata:()=>l,toc:()=>o});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.yg)("p",null,"Written in ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.yg)("p",null,"The GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.yg)("div",{class:"alert alert--warning"},"Right now, there is no way to explicitly declare a GraphQL interface using GraphQLite.",(0,i.yg)("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.8794de2a.js b/assets/js/38cf1c7a.7604d7f6.js similarity index 99% rename from assets/js/38cf1c7a.8794de2a.js rename to assets/js/38cf1c7a.7604d7f6.js index 4fe12de97..189e899f4 100644 --- a/assets/js/38cf1c7a.8794de2a.js +++ b/assets/js/38cf1c7a.7604d7f6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5409],{41174:(e,n,i)=>{i.r(n),i.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var t=i(58168),a=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,t.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour\nof a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:i(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library."),(0,a.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"OnlyDebug.php")),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:",(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"li"},"graphql.field_middleware")," tag.")))}c.isMDXComponent=!0},8643:(e,n,i)=>{i.d(n,{A:()=>t});const t=i.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5409],{41174:(e,n,i)=>{i.r(n),i.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var t=i(58168),a=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,t.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour\nof a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:i(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/index.html"},"doctrine/annotations")," library."),(0,a.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"OnlyDebug.php")),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:",(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"li"},"graphql.field_middleware")," tag.")))}c.isMDXComponent=!0},8643:(e,n,i)=>{i.d(n,{A:()=>t});const t=i.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/394f3211.eee0aecd.js b/assets/js/394f3211.4e1435c5.js similarity index 99% rename from assets/js/394f3211.eee0aecd.js rename to assets/js/394f3211.4e1435c5.js index 5440b4882..8bc299d75 100644 --- a/assets/js/394f3211.eee0aecd.js +++ b/assets/js/394f3211.4e1435c5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6700],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>q});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),i=a(56347),s=a(57485),u=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.W6)(),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.aZ)(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]=y({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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),m=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);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 m=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":i===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 w(e){const t=g(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function q(e){const t=(0,m.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},71103:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>u});var n=a(58168),r=(a(96540),a(15680));a(67443),a(11470),a(19365);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/6.1/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/queries.mdx",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/6.1/other-frameworks"},next:{title:"Mutations",permalink:"/docs/6.1/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.yg)(c,(0,n.A)({},p,l,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.yg)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.yg)("p",null,"Read the ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.1/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:a(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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},67258:(e,t,a)=>{a.d(t,{A:()=>n});const n=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6700],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>q});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),i=a(56347),s=a(57485),u=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.W6)(),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.aZ)(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]=y({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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),m=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);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 m=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":i===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 w(e){const t=g(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function q(e){const t=(0,m.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},71103:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>u});var n=a(58168),r=(a(96540),a(15680));a(67443),a(11470),a(19365);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/6.1/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/queries.mdx",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/6.1/other-frameworks"},next:{title:"Mutations",permalink:"/docs/6.1/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.yg)(c,(0,n.A)({},p,l,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.yg)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.yg)("p",null,"Read the ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.1/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:a(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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},67258:(e,t,a)=>{a.d(t,{A:()=>n});const n=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/3a3e6a89.82f09992.js b/assets/js/3a3e6a89.777b0fc3.js similarity index 99% rename from assets/js/3a3e6a89.82f09992.js rename to assets/js/3a3e6a89.777b0fc3.js index a5d00efb4..8dc5aeab6 100644 --- a/assets/js/3a3e6a89.82f09992.js +++ b/assets/js/3a3e6a89.777b0fc3.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3565],{89404:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},l=void 0,o={unversionedId:"symfony-bundle",id:"version-8.0.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-8.0.0/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-8.0.0/symfony-bundle.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,i.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Now, go to the ",(0,i.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,i.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},l=void 0,o={unversionedId:"symfony-bundle",id:"version-8.0.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-8.0.0/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-8.0.0/symfony-bundle.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,i.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Now, go to the ",(0,i.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,i.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8100],{70177:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/3b58261a.8918d844.js b/assets/js/3b58261a.66c89998.js similarity index 98% rename from assets/js/3b58261a.8918d844.js rename to assets/js/3b58261a.66c89998.js index f5c55752a..b05b3b3aa 100644 --- a/assets/js/3b58261a.8918d844.js +++ b/assets/js/3b58261a.66c89998.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5473],{13053:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>l,default:()=>m,frontMatter:()=>r,metadata:()=>s,toc:()=>c});var a=t(58168),i=(t(96540),t(15680));t(67443);const r={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},l=void 0,s={unversionedId:"inheritance-interfaces",id:"version-8.0.0/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/inheritance-interfaces.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:n,...t}=e;return(0,i.yg)(g,(0,a.A)({},o,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,i.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.yg)("p",null,"Written in ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.yg)("p",null,"The GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,i.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute on a PHP interface."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n")),(0,i.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,i.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.yg)("p",null,"This will translate in GraphQL schema as:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,i.yg)("p",null,"Please note that you do not need to put the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute again in the implementing class."),(0,i.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,i.yg)("p",null,"You don't have to explicitly put a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute on the class implementing the interface (though this\nis usually a good idea)."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute, GraphQLite will\ncreate a ",(0,i.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,i.yg)("pre",null,(0,i.yg)("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([[5473],{13053:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>l,default:()=>m,frontMatter:()=>r,metadata:()=>s,toc:()=>c});var a=t(58168),i=(t(96540),t(15680));t(67443);const r={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},l=void 0,s={unversionedId:"inheritance-interfaces",id:"version-8.0.0/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/inheritance-interfaces.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:n,...t}=e;return(0,i.yg)(g,(0,a.A)({},o,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,i.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.yg)("p",null,"Written in ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.yg)("p",null,"The GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,i.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute on a PHP interface."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n")),(0,i.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,i.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.yg)("p",null,"This will translate in GraphQL schema as:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,i.yg)("p",null,"Please note that you do not need to put the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute again in the implementing class."),(0,i.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,i.yg)("p",null,"You don't have to explicitly put a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute on the class implementing the interface (though this\nis usually a good idea)."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute, GraphQLite will\ncreate a ",(0,i.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,i.yg)("pre",null,(0,i.yg)("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/3c86ad25.fffa6c7c.js b/assets/js/3c86ad25.272dcc24.js similarity index 94% rename from assets/js/3c86ad25.fffa6c7c.js rename to assets/js/3c86ad25.272dcc24.js index acbe62005..65d071a08 100644 --- a/assets/js/3c86ad25.fffa6c7c.js +++ b/assets/js/3c86ad25.272dcc24.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1587],{24002:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"version-8.0.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-8.0.0/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-8.0.0/getting-started.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:l},g="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,r.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1587],{24002:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"version-8.0.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-8.0.0/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-8.0.0/getting-started.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:l},g="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,r.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/3d0eb74d.ea970a87.js b/assets/js/3d0eb74d.caf36d3c.js similarity index 99% rename from assets/js/3d0eb74d.ea970a87.js rename to assets/js/3d0eb74d.caf36d3c.js index f1fea818f..577a968e1 100644 --- a/assets/js/3d0eb74d.ea970a87.js +++ b/assets/js/3d0eb74d.caf36d3c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5558],{10381:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,i.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Now, go to the ",(0,i.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,i.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,i.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Now, go to the ",(0,i.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,i.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(i.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>I});var a=n(58168),r=n(96540),i=n(20053),o=n(23104),l=n(56347),u=n(57485),s=n(31682),p=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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=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(!y({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}),[c,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,p.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),h=(()=>{const e=u??c;return y({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{h&&l(h)}),[h]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!y({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 h=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=s[n].value;a!==l&&(c(t),u(a))},y=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.A)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>p.push(e),onKeyDown:y,onClick:d},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(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=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function I(e){const t=(0,h.A)();return r.createElement(N,(0,a.A)({key:String(t)},e))}},33591:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>s});var a=n(58168),r=(n(96540),n(15680));n(67443),n(11470),n(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"docs",previous:{title:"External type declaration",permalink:"/docs/6.1/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/6.1/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.yg)(c,(0,a.A)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,r.yg)("p",null,"Your GraphQL query might look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,r.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,r.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,r.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,r.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,r.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,r.yg)("a",{parentName:"p",href:"#input-attribute"},(0,r.yg)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,r.yg)("a",{parentName:"p",href:"#factory"},"Factory method"),"."),(0,r.yg)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,r.yg)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now if you call the ",(0,r.yg)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,r.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,r.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,r.yg)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,r.yg)("p",null,"There are some important things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized on properties for Input Type, as well as setters."),(0,r.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,r.yg)("ul",{parentName:"li"},(0,r.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,r.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on the setter, instead of the property, allowing you to have use many other attributes (",(0,r.yg)("inlineCode",{parentName:"li"},"Security"),", ",(0,r.yg)("inlineCode",{parentName:"li"},"Right"),", ",(0,r.yg)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,r.yg)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,r.yg)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,r.yg)("li",{parentName:"ul"},"It's advised to use the ",(0,r.yg)("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.yg)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,r.yg)("p",null,"Simple usage of the ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,r.yg)("inlineCode",{parentName:"p"},"Location")," class."),(0,r.yg)("p",null,"You can add multiple ",(0,r.yg)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"There are 2 input types added to the ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,r.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,r.yg)("li",{parentName:"ul"},"Field ",(0,r.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,r.yg)("li",{parentName:"ul"},"Field ",(0,r.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,r.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,r.yg)("li",{parentName:"ul"},"Field ",(0,r.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,r.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,r.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,r.yg)("li",{parentName:"ul"},"Field ",(0,r.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,r.yg)("p",null,"Note that ",(0,r.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,r.yg)("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.yg)("h2",{id:"factory"},"Factory"),(0,r.yg)("p",null,"A ",(0,r.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,r.yg)("p",null,"Here is an example of factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,r.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,r.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,r.yg)("p",null,"A few important things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,r.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,r.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,r.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n")),(0,r.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,r.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,r.yg)("p",null,"Here is an annotated sample:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("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.yg)("p",null,"Image your ",(0,r.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,r.yg)("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([[2235],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(i.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>I});var a=n(58168),r=n(96540),i=n(20053),o=n(23104),l=n(56347),u=n(57485),s=n(31682),p=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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=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(!y({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}),[c,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,p.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),h=(()=>{const e=u??c;return y({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{h&&l(h)}),[h]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!y({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 h=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:l,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),d=e=>{const t=e.currentTarget,n=p.indexOf(t),a=s[n].value;a!==l&&(c(t),u(a))},y=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.A)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>p.push(e),onKeyDown:y,onClick:d},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(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=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function I(e){const t=(0,h.A)();return r.createElement(N,(0,a.A)({key:String(t)},e))}},33591:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>s});var a=n(58168),r=(n(96540),n(15680));n(67443),n(11470),n(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"docs",previous:{title:"External type declaration",permalink:"/docs/6.1/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/6.1/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.yg)(c,(0,a.A)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,r.yg)("p",null,"Your GraphQL query might look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,r.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,r.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,r.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,r.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,r.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,r.yg)("a",{parentName:"p",href:"#input-attribute"},(0,r.yg)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,r.yg)("a",{parentName:"p",href:"#factory"},"Factory method"),"."),(0,r.yg)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,r.yg)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now if you call the ",(0,r.yg)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,r.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,r.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,r.yg)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,r.yg)("p",null,"There are some important things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized on properties for Input Type, as well as setters."),(0,r.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,r.yg)("ul",{parentName:"li"},(0,r.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,r.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on the setter, instead of the property, allowing you to have use many other attributes (",(0,r.yg)("inlineCode",{parentName:"li"},"Security"),", ",(0,r.yg)("inlineCode",{parentName:"li"},"Right"),", ",(0,r.yg)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,r.yg)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,r.yg)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,r.yg)("li",{parentName:"ul"},"It's advised to use the ",(0,r.yg)("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.yg)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,r.yg)("p",null,"Simple usage of the ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,r.yg)("inlineCode",{parentName:"p"},"Location")," class."),(0,r.yg)("p",null,"You can add multiple ",(0,r.yg)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"There are 2 input types added to the ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,r.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,r.yg)("li",{parentName:"ul"},"Field ",(0,r.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,r.yg)("li",{parentName:"ul"},"Field ",(0,r.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,r.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,r.yg)("li",{parentName:"ul"},"Field ",(0,r.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,r.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,r.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,r.yg)("li",{parentName:"ul"},"Field ",(0,r.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,r.yg)("p",null,"Note that ",(0,r.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,r.yg)("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.yg)("h2",{id:"factory"},"Factory"),(0,r.yg)("p",null,"A ",(0,r.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,r.yg)("p",null,"Here is an example of factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,r.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,r.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,r.yg)("p",null,"A few important things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,r.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,r.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,r.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n")),(0,r.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,r.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,r.yg)("p",null,"Here is an annotated sample:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("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.yg)("p",null,"Image your ",(0,r.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,r.yg)("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.c6af0b12.js b/assets/js/3f944aba.b52fcb1d.js similarity index 98% rename from assets/js/3f944aba.c6af0b12.js rename to assets/js/3f944aba.b52fcb1d.js index b54c72028..2129f94bc 100644 --- a/assets/js/3f944aba.c6af0b12.js +++ b/assets/js/3f944aba.b52fcb1d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3585],{23458:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/4.2/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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([[3585],{23458:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/4.2/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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.ff156576.js b/assets/js/400ddbbb.1bebe130.js similarity index 99% rename from assets/js/400ddbbb.ff156576.js rename to assets/js/400ddbbb.1bebe130.js index f76b07c27..17785ddd2 100644 --- a/assets/js/400ddbbb.ff156576.js +++ b/assets/js/400ddbbb.1bebe130.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6961],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(o.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>A});var n=a(58168),r=a(96540),o=a(20053),u=a(23104),l=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(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 T(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},r.createElement(g,(0,n.A)({},e,t)),r.createElement(y,(0,n.A)({},e,t)))}function A(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},42342:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),o=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(m,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, mutations are created ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/queries"},"like queries"),"."),(0,r.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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([[6961],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(o.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>A});var n=a(58168),r=a(96540),o=a(20053),u=a(23104),l=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(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 T(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},r.createElement(g,(0,n.A)({},e,t)),r.createElement(y,(0,n.A)({},e,t)))}function A(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},42342:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),o=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(m,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, mutations are created ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/queries"},"like queries"),"."),(0,r.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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/4194805f.f56ce99b.js b/assets/js/4194805f.4897f28c.js similarity index 99% rename from assets/js/4194805f.f56ce99b.js rename to assets/js/4194805f.4897f28c.js index ed18fe4b6..42c4ddb53 100644 --- a/assets/js/4194805f.f56ce99b.js +++ b/assets/js/4194805f.4897f28c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7116],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),g(e)}),[u,g,i]),tabValues:i}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function T(e){const t=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},20142:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),i=(a(67443),a(11470)),o=a(19365);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},s=void 0,u={unversionedId:"autowiring",id:"version-7.0.0/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-7.0.0/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/7.0.0/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/autowiring.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"docs",previous:{title:"Type mapping",permalink:"/docs/7.0.0/type-mapping"},next:{title:"Extending a type",permalink:"/docs/7.0.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,...a}=e;return(0,r.yg)(h,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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([[7116],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),g(e)}),[u,g,i]),tabValues:i}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function T(e){const t=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},20142:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),i=(a(67443),a(11470)),o=a(19365);const l={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},s=void 0,u={unversionedId:"autowiring",id:"version-7.0.0/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-7.0.0/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/7.0.0/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/autowiring.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},sidebar:"docs",previous:{title:"Type mapping",permalink:"/docs/7.0.0/type-mapping"},next:{title:"Extending a type",permalink:"/docs/7.0.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,...a}=e;return(0,r.yg)(h,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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/4445fe20.841208ca.js b/assets/js/4445fe20.9022a165.js similarity index 98% rename from assets/js/4445fe20.841208ca.js rename to assets/js/4445fe20.9022a165.js index c055e7512..2c0c7c041 100644 --- a/assets/js/4445fe20.841208ca.js +++ b/assets/js/4445fe20.9022a165.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3811],{828:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>d,frontMatter:()=>r,metadata:()=>a,toc:()=>c});var o=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"subscriptions",title:"Subscriptions",sidebar_label:"Subscriptions"},s=void 0,a={unversionedId:"subscriptions",id:"version-8.0.0/subscriptions",title:"Subscriptions",description:"In GraphQLite, subscriptions are created like queries or mutations.",source:"@site/versioned_docs/version-8.0.0/subscriptions.mdx",sourceDirName:".",slug:"/subscriptions",permalink:"/docs/subscriptions",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/subscriptions.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"subscriptions",title:"Subscriptions",sidebar_label:"Subscriptions"},sidebar:"docs",previous:{title:"Mutations",permalink:"/docs/mutations"},next:{title:"Type mapping",permalink:"/docs/type-mapping"}},p={},c=[],l={toc:c},u="wrapper";function d(e){let{components:t,...n}=e;return(0,i.yg)(u,(0,o.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, subscriptions are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/queries"},"like queries")," or ",(0,i.yg)("a",{parentName:"p",href:"/docs/mutations"},"mutations"),"."),(0,i.yg)("p",null,"To create a subscription, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Subscription(outputType: 'Product')]\n public function productAdded(?ID $categoryId = null): void\n {\n // Some code that sets up any connections, stores the subscription details, etc.\n }\n}\n")),(0,i.yg)("p",null,"As you will notice in the above example, we're returning ",(0,i.yg)("inlineCode",{parentName:"p"},"void"),". In general, this is probably the\ncorrect return type."),(0,i.yg)("p",null,"You could, however, type the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," as the return type of the method, instead\nof using the ",(0,i.yg)("inlineCode",{parentName:"p"},"outputType")," argument on the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute. This means you\nwould have to return an instance of ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," from the method though. One exception here, is if\nyou intend to use PHP for your long-running streaming process, you could block the process inside\nthe controller and basically never return anything from the method, just terminating the\nconnection/stream when it breaks, or when the client disconnects."),(0,i.yg)("p",null,"Most implementations will want to offload the actual real-time streaming connection to a better suited\ntechnology, like SSE (server-sent events), WebSockets, etc. GraphQLite does not make any assumptions\nhere. Therefore, it's most practical to return ",(0,i.yg)("inlineCode",{parentName:"p"},"void")," from the controller method. Since GraphQL\nis a strictly typed spec, we cannot return anything other than the defined ",(0,i.yg)("inlineCode",{parentName:"p"},"outputType")," from the request.\nThat would be a violation of the GraphQL specification. Returning ",(0,i.yg)("inlineCode",{parentName:"p"},"void"),", which is translated to ",(0,i.yg)("inlineCode",{parentName:"p"},"null"),"\nin the GraphQL response body, allows for us to complete the request and terminate the PHP process."),(0,i.yg)("p",null,"We recommend using response headers to pass back any necessary information realted to the subscription.\nThis might be a subscription ID, a streaming server URL to connect to, or whatever you need to pass\nback to the client."),(0,i.yg)("div",{class:"alert alert--info"},"In the future, it may make sense to implement streaming servers directly into GraphQLite, especially as PHP progresses with async and parallel processing. At this time, we might consider returning a `Generator` (or `Fiber`) from the controller method."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3811],{828:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>d,frontMatter:()=>r,metadata:()=>a,toc:()=>c});var o=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"subscriptions",title:"Subscriptions",sidebar_label:"Subscriptions"},s=void 0,a={unversionedId:"subscriptions",id:"version-8.0.0/subscriptions",title:"Subscriptions",description:"In GraphQLite, subscriptions are created like queries or mutations.",source:"@site/versioned_docs/version-8.0.0/subscriptions.mdx",sourceDirName:".",slug:"/subscriptions",permalink:"/docs/subscriptions",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/subscriptions.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"subscriptions",title:"Subscriptions",sidebar_label:"Subscriptions"},sidebar:"docs",previous:{title:"Mutations",permalink:"/docs/mutations"},next:{title:"Type mapping",permalink:"/docs/type-mapping"}},p={},c=[],l={toc:c},u="wrapper";function d(e){let{components:t,...n}=e;return(0,i.yg)(u,(0,o.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, subscriptions are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/queries"},"like queries")," or ",(0,i.yg)("a",{parentName:"p",href:"/docs/mutations"},"mutations"),"."),(0,i.yg)("p",null,"To create a subscription, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"namespace App\\Controller;\n\nuse TheCodingMachine\\GraphQLite\\Annotations\\Mutation;\n\nclass ProductController\n{\n #[Subscription(outputType: 'Product')]\n public function productAdded(?ID $categoryId = null): void\n {\n // Some code that sets up any connections, stores the subscription details, etc.\n }\n}\n")),(0,i.yg)("p",null,"As you will notice in the above example, we're returning ",(0,i.yg)("inlineCode",{parentName:"p"},"void"),". In general, this is probably the\ncorrect return type."),(0,i.yg)("p",null,"You could, however, type the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," as the return type of the method, instead\nof using the ",(0,i.yg)("inlineCode",{parentName:"p"},"outputType")," argument on the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute. This means you\nwould have to return an instance of ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," from the method though. One exception here, is if\nyou intend to use PHP for your long-running streaming process, you could block the process inside\nthe controller and basically never return anything from the method, just terminating the\nconnection/stream when it breaks, or when the client disconnects."),(0,i.yg)("p",null,"Most implementations will want to offload the actual real-time streaming connection to a better suited\ntechnology, like SSE (server-sent events), WebSockets, etc. GraphQLite does not make any assumptions\nhere. Therefore, it's most practical to return ",(0,i.yg)("inlineCode",{parentName:"p"},"void")," from the controller method. Since GraphQL\nis a strictly typed spec, we cannot return anything other than the defined ",(0,i.yg)("inlineCode",{parentName:"p"},"outputType")," from the request.\nThat would be a violation of the GraphQL specification. Returning ",(0,i.yg)("inlineCode",{parentName:"p"},"void"),", which is translated to ",(0,i.yg)("inlineCode",{parentName:"p"},"null"),"\nin the GraphQL response body, allows for us to complete the request and terminate the PHP process."),(0,i.yg)("p",null,"We recommend using response headers to pass back any necessary information realted to the subscription.\nThis might be a subscription ID, a streaming server URL to connect to, or whatever you need to pass\nback to the client."),(0,i.yg)("div",{class:"alert alert--info"},"In the future, it may make sense to implement streaming servers directly into GraphQLite, especially as PHP progresses with async and parallel processing. At this time, we might consider returning a `Generator` (or `Fiber`) from the controller method."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/471c3e37.63dc4aba.js b/assets/js/471c3e37.a2aad2f1.js similarity index 99% rename from assets/js/471c3e37.63dc4aba.js rename to assets/js/471c3e37.a2aad2f1.js index 9a9f38d85..b969bf7ba 100644 --- a/assets/js/471c3e37.63dc4aba.js +++ b/assets/js/471c3e37.a2aad2f1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8166],{9753:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>g,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=a(58168),r=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom attributes",permalink:"/docs/next/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/next/extend-input-type"}},s={},p=[{value:"Attributes parsing",id:"attributes-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},u="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(u,(0,n.A)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Autowire]")," attribute")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Validate]")," attribute (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"attributes-parsing"},"Attributes parsing"),(0,r.yg)("p",null,"If you plan to use attributes while resolving arguments, your attribute class should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Autowire]"),"."),(0,r.yg)("p",null,"We only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The class looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this attribute to autowire a service from the container into a given parameter of a field/query/mutation.\n *\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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8166],{9753:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>g,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=a(58168),r=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom attributes",permalink:"/docs/next/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/next/extend-input-type"}},s={},p=[{value:"Attributes parsing",id:"attributes-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},u="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(u,(0,n.A)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Autowire]")," attribute")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Validate]")," attribute (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"attributes-parsing"},"Attributes parsing"),(0,r.yg)("p",null,"If you plan to use attributes while resolving arguments, your attribute class should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Autowire]"),"."),(0,r.yg)("p",null,"We only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The class looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this attribute to autowire a service from the container into a given parameter of a field/query/mutation.\n *\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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/48fde361.7161dff2.js b/assets/js/48fde361.156e0f5a.js similarity index 99% rename from assets/js/48fde361.7161dff2.js rename to assets/js/48fde361.156e0f5a.js index 79d5d69b3..bd054b1bb 100644 --- a/assets/js/48fde361.7161dff2.js +++ b/assets/js/48fde361.156e0f5a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[958],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var t=a(96540),r=a(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),l=a(20053),i=a(23104),s=a(56347),p=a(57485),c=a(31682),o=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function m(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function d(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function y(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[p,c]=g({queryString:a,groupId:t}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{h&&s(h)}),[h]);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),y(e)}),[c,y,l]),tabValues:l}}var h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=c[a].value;t!==s&&(u(n),p(t))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return r.createElement("li",(0,t.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function N(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(v,(0,t.A)({},e,n)))}function T(e){const n=(0,h.A)();return r.createElement(N,(0,t.A)({key:String(n)},e))}},64674:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>g,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var t=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...a}=e;return(0,r.yg)(d,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.yg)("p",null,"Written in ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.yg)("p",null,"The GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.yg)("p",null,"This will translate in GraphQL schema as:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.yg)("p",null,"Please note that you do not need to put the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.yg)("p",null,"You don't have to explicitly put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[958],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var t=a(96540),r=a(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),l=a(20053),i=a(23104),s=a(56347),p=a(57485),c=a(31682),o=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function m(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function d(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function y(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[p,c]=g({queryString:a,groupId:t}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{h&&s(h)}),[h]);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),y(e)}),[c,y,l]),tabValues:l}}var h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=c[a].value;t!==s&&(u(n),p(t))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return r.createElement("li",(0,t.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function N(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(v,(0,t.A)({},e,n)))}function T(e){const n=(0,h.A)();return r.createElement(N,(0,t.A)({key:String(n)},e))}},64674:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>g,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var t=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...a}=e;return(0,r.yg)(d,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.yg)("p",null,"Written in ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.yg)("p",null,"The GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.yg)("p",null,"This will translate in GraphQL schema as:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.yg)("p",null,"Please note that you do not need to put the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.yg)("p",null,"You don't have to explicitly put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4a060504.b56ac654.js b/assets/js/4a060504.af38cde8.js similarity index 99% rename from assets/js/4a060504.b56ac654.js rename to assets/js/4a060504.af38cde8.js index 10eaa6321..2df801b28 100644 --- a/assets/js/4a060504.b56ac654.js +++ b/assets/js/4a060504.af38cde8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8997],{69495:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/4.3/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/4.3/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8997],{69495:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/4.3/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/4.3/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4a07aaf0.8c69c63d.js b/assets/js/4a07aaf0.9d21528d.js similarity index 98% rename from assets/js/4a07aaf0.8c69c63d.js rename to assets/js/4a07aaf0.9d21528d.js index f40cb366b..86771b88e 100644 --- a/assets/js/4a07aaf0.8c69c63d.js +++ b/assets/js/4a07aaf0.9d21528d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8621],{19365:(e,t,n)=>{n.d(t,{A:()=>u});var a=n(96540),r=n(20053);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.A)(l.tabItem,u),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>q});var a=n(58168),r=n(96540),l=n(20053),u=n(23104),o=n(56347),s=n(57485),i=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);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 y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),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.A)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:u}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.tabItem,u?.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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function q(e){const t=(0,y.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},14101:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),u=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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([[8621],{19365:(e,t,n)=>{n.d(t,{A:()=>u});var a=n(96540),r=n(20053);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.A)(l.tabItem,u),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>q});var a=n(58168),r=n(96540),l=n(20053),u=n(23104),o=n(56347),s=n(57485),i=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);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 y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),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.A)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:u}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.tabItem,u?.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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function q(e){const t=(0,y.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},14101:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),u=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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.512b4df8.js b/assets/js/4a2da18c.28608207.js similarity index 99% rename from assets/js/4a2da18c.512b4df8.js rename to assets/js/4a2da18c.28608207.js index d9c6bf58d..ab371c60c 100644 --- a/assets/js/4a2da18c.512b4df8.js +++ b/assets/js/4a2da18c.28608207.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6537],{34823:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(58168),a=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:t(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,n,t)=>{t.d(n,{A:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6537],{34823:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(58168),a=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:t(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,n,t)=>{t.d(n,{A:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/4aab8b8c.5edf73c4.js b/assets/js/4aab8b8c.ff6f0690.js similarity index 99% rename from assets/js/4aab8b8c.5edf73c4.js rename to assets/js/4aab8b8c.ff6f0690.js index 4d62de185..9756e5082 100644 --- a/assets/js/4aab8b8c.5edf73c4.js +++ b/assets/js/4aab8b8c.ff6f0690.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3126],{81853:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>m});var t=a(58168),r=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:n,...a}=e;return(0,r.yg)(g,(0,t.A)({},p,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"li"},"ResolveInfo")," object. For instance:",(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"li"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware"))),(0,r.yg)("li",{parentName:"ul"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,r.yg)("li",{parentName:"ul"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Validate")," annotation (in Laravel package)")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middleware class")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter resolver class")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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([[3126],{81853:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>m});var t=a(58168),r=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:n,...a}=e;return(0,r.yg)(g,(0,t.A)({},p,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"li"},"ResolveInfo")," object. For instance:",(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"li"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware"))),(0,r.yg)("li",{parentName:"ul"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,r.yg)("li",{parentName:"ul"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Validate")," annotation (in Laravel package)")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middleware class")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter resolver class")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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/4bdafdff.edd05d37.js b/assets/js/4bdafdff.a73df832.js similarity index 99% rename from assets/js/4bdafdff.edd05d37.js rename to assets/js/4bdafdff.a73df832.js index 57e669427..3369d115f 100644 --- a/assets/js/4bdafdff.edd05d37.js +++ b/assets/js/4bdafdff.a73df832.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[222],{27612:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>p,toc:()=>y});var n=a(58168),l=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},g={},y=[{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}],o={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},o,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.yg)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.yg)("h2",{id:"query"},"@Query"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation"},"@Mutation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type"},"@Type"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("a",{parentName:"p",href:"#input-annotation"},"@Input annotation")," directly on the input type or a ",(0,l.yg)("a",{parentName:"p",href:"#factory-annotation"},"@Factory annoation")," to make/return an input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("em",{parentName:"td"},"is passed"),", ",(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/external-type-declaration"},"the class/enum annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," becomes a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("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.yg)("h2",{id:"extendtype"},"@ExtendType"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/extend-type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"input"},"@Input"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,l.yg)("inlineCode",{parentName:"td"},"true")," ",(0,l.yg)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,l.yg)("inlineCode",{parentName:"td"},"true")," when ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"update"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.yg)("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.yg)("h2",{id:"field"},"@Field"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.yg)("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.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"for"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string, array"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/input-types"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.yg)("h2",{id:"sourcefield"},"@SourceField"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield"},"@MagicField"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"logged"},"@Logged"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right"},"@Right"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith"},"@FailWith"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"value"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized"},"@HideIfUnauthorized"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser"},"@InjectUser"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security"},"@Security"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory"},"@Factory"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("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.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype"},"@UseInputType"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate"},"@Decorate"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire"},"@Autowire"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter"},"@HideParameter"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"validate"},"@Validate"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion"},"@Assertion"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype"},(0,l.yg)("del",{parentName:"h2"},"@EnumType")),(0,l.yg)("p",null,(0,l.yg)("em",{parentName:"p"},"Deprecated: Use ",(0,l.yg)("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.yg)("a",{parentName:"em",href:"#type-annotation"},"@Type"),".")),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[222],{27612:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>p,toc:()=>y});var n=a(58168),l=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},g={},y=[{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}],o={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},o,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.yg)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.yg)("h2",{id:"query"},"@Query"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation"},"@Mutation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type"},"@Type"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("a",{parentName:"p",href:"#input-annotation"},"@Input annotation")," directly on the input type or a ",(0,l.yg)("a",{parentName:"p",href:"#factory-annotation"},"@Factory annoation")," to make/return an input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("em",{parentName:"td"},"is passed"),", ",(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/external-type-declaration"},"the class/enum annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," becomes a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("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.yg)("h2",{id:"extendtype"},"@ExtendType"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/extend-type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"input"},"@Input"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,l.yg)("inlineCode",{parentName:"td"},"true")," ",(0,l.yg)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,l.yg)("inlineCode",{parentName:"td"},"true")," when ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"update"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.yg)("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.yg)("h2",{id:"field"},"@Field"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.yg)("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.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"for"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string, array"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/input-types"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.yg)("h2",{id:"sourcefield"},"@SourceField"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield"},"@MagicField"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"logged"},"@Logged"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right"},"@Right"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith"},"@FailWith"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"value"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized"},"@HideIfUnauthorized"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser"},"@InjectUser"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security"},"@Security"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory"},"@Factory"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("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.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype"},"@UseInputType"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate"},"@Decorate"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire"},"@Autowire"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter"},"@HideParameter"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"validate"},"@Validate"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion"},"@Assertion"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype"},(0,l.yg)("del",{parentName:"h2"},"@EnumType")),(0,l.yg)("p",null,(0,l.yg)("em",{parentName:"p"},"Deprecated: Use ",(0,l.yg)("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.yg)("a",{parentName:"em",href:"#type-annotation"},"@Type"),".")),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4c5bf49d.322bc4b8.js b/assets/js/4c5bf49d.21adcfe4.js similarity index 99% rename from assets/js/4c5bf49d.322bc4b8.js rename to assets/js/4c5bf49d.21adcfe4.js index 78ed0dfb4..d2f3cefc0 100644 --- a/assets/js/4c5bf49d.322bc4b8.js +++ b/assets/js/4c5bf49d.21adcfe4.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2720],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(o.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),o=a(20053),u=a(23104),l=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(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 A(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},r.createElement(g,(0,n.A)({},e,t)),r.createElement(y,(0,n.A)({},e,t)))}function T(e){const t=(0,f.A)();return r.createElement(A,(0,n.A)({key:String(t)},e))}},51969:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),o=(a(67443),a(11470)),u=a(19365);const l={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,i={unversionedId:"mutations",id:"version-7.0.0/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-7.0.0/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/7.0.0/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/mutations.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/7.0.0/queries"},next:{title:"Subscriptions",permalink:"/docs/7.0.0/subscriptions"}},c={},d=[],p={toc:d},m="wrapper";function b(e){let{components:t,...a}=e;return(0,r.yg)(m,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, mutations are created ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/queries"},"like queries"),"."),(0,r.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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([[2720],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(o.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),o=a(20053),u=a(23104),l=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(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 A(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},r.createElement(g,(0,n.A)({},e,t)),r.createElement(y,(0,n.A)({},e,t)))}function T(e){const t=(0,f.A)();return r.createElement(A,(0,n.A)({key:String(t)},e))}},51969:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),o=(a(67443),a(11470)),u=a(19365);const l={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,i={unversionedId:"mutations",id:"version-7.0.0/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-7.0.0/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/7.0.0/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/mutations.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/7.0.0/queries"},next:{title:"Subscriptions",permalink:"/docs/7.0.0/subscriptions"}},c={},d=[],p={toc:d},m="wrapper";function b(e){let{components:t,...a}=e;return(0,r.yg)(m,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, mutations are created ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/queries"},"like queries"),"."),(0,r.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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/4c7f7507.76a2b02b.js b/assets/js/4c7f7507.2c7ce80d.js similarity index 99% rename from assets/js/4c7f7507.76a2b02b.js rename to assets/js/4c7f7507.2c7ce80d.js index 8211cce41..25c265fb2 100644 --- a/assets/js/4c7f7507.76a2b02b.js +++ b/assets/js/4c7f7507.2c7ce80d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9472],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var t=a(96540),r=a(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),l=a(20053),i=a(23104),s=a(56347),p=a(57485),c=a(31682),o=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function m(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function d(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function h(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[p,c]=g({queryString:a,groupId:t}),[u,h]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),y=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&s(y)}),[y]);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),h(e)}),[c,h,l]),tabValues:l}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=c[a].value;t!==s&&(u(n),p(t))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return r.createElement("li",(0,t.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function N(e){const n=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(v,(0,t.A)({},e,n)))}function T(e){const n=(0,y.A)();return r.createElement(N,(0,t.A)({key:String(n)},e))}},34844:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>g,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var t=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...a}=e;return(0,r.yg)(d,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.yg)("p",null,"Written in ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.yg)("p",null,"The GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.yg)("p",null,"This will translate in GraphQL schema as:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.yg)("p",null,"Please note that you do not need to put the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.yg)("p",null,"You don't have to explicitly put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9472],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var t=a(96540),r=a(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),l=a(20053),i=a(23104),s=a(56347),p=a(57485),c=a(31682),o=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function m(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function d(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function h(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[p,c]=g({queryString:a,groupId:t}),[u,h]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),y=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&s(y)}),[y]);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),h(e)}),[c,h,l]),tabValues:l}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=c[a].value;t!==s&&(u(n),p(t))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return r.createElement("li",(0,t.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function N(e){const n=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(v,(0,t.A)({},e,n)))}function T(e){const n=(0,y.A)();return r.createElement(N,(0,t.A)({key:String(n)},e))}},34844:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>g,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var t=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...a}=e;return(0,r.yg)(d,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.yg)("p",null,"Written in ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.yg)("p",null,"The GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.yg)("p",null,"This will translate in GraphQL schema as:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.yg)("p",null,"Please note that you do not need to put the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.yg)("p",null,"You don't have to explicitly put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4d00e03a.99c1a8d5.js b/assets/js/4d00e03a.e54ebabe.js similarity index 99% rename from assets/js/4d00e03a.99c1a8d5.js rename to assets/js/4d00e03a.e54ebabe.js index 801c618fd..47b7c3755 100644 --- a/assets/js/4d00e03a.99c1a8d5.js +++ b/assets/js/4d00e03a.e54ebabe.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8688],{36428:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>r,default:()=>g,frontMatter:()=>l,metadata:()=>o,toc:()=>d});var t=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:a,...n}=e;return(0,i.yg)(u,(0,t.A)({},s,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h4",{id:"new-features"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/input-types#input-annotation"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h4",{id:"new-features-1"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h4",{id:"new-features-2"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("h4",{id:"symfony"},"Symfony:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h4",{id:"laravel"},"Laravel:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h4",{id:"internals"},"Internals:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8688],{36428:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>r,default:()=>g,frontMatter:()=>l,metadata:()=>o,toc:()=>d});var t=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:a,...n}=e;return(0,i.yg)(u,(0,t.A)({},s,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h4",{id:"new-features"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/input-types#input-annotation"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h4",{id:"new-features-1"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h4",{id:"new-features-2"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("h4",{id:"symfony"},"Symfony:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h4",{id:"laravel"},"Laravel:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.2/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h4",{id:"internals"},"Internals:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4d049718.9120e91e.js b/assets/js/4d049718.c6fcb28d.js similarity index 99% rename from assets/js/4d049718.9120e91e.js rename to assets/js/4d049718.c6fcb28d.js index 23356be1a..39f121ac3 100644 --- a/assets/js/4d049718.9120e91e.js +++ b/assets/js/4d049718.c6fcb28d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2156],{19365:(e,n,t)=>{t.d(n,{A:()=>r});var a=t(96540),o=t(20053);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.A)(i.tabItem,r),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>A});var a=t(58168),o=t(96540),i=t(20053),r=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.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:o}}=e;return{value:n,label:t,attributes:a,default:o}}))}function d(e){const{values:n,children:t}=e;return(0,o.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 y(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,l.W6)(),i=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.aZ)(i),(0,o.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.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(!y({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:i}))),[u,s]=h({queryString:t,groupId:a}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,o.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),m=(()=>{const e=u??p;return y({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{m&&l(m)}),[m]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!y({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(p(n),u(a))},y=e=>{let n=null;switch(e.key){case"Enter":d(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 o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:r}=e;return o.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:y,onClick:d},r,{className:(0,i.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===n})}),t??n)})))}function T(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,o.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=g(e);return o.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},o.createElement(b,(0,a.A)({},e,n)),o.createElement(T,(0,a.A)({},e,n)))}function A(e){const n=(0,m.A)();return o.createElement(v,(0,a.A)({key:String(n)},e))}},38556:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>h,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=t(58168),o=(t(96540),t(15680)),i=(t(67443),t(11470)),r=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:n,...t}=e;return(0,o.yg)(y,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.yg)("p",null,"For instance:"),(0,o.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,o.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.yg)("p",null,"GraphQLite allows you to use a ",(0,o.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!")," The ",(0,o.yg)("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.yg)("br",null),(0,o.yg)("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.yg)("p",null,"In methods with a ",(0,o.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.yg)("h2",{id:"sourcefield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.yg)("p",null,"If you don't want to rewrite all ",(0,o.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.yg)("p",null,"You can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("h2",{id:"magicfield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"You can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"Any annotations described in the ",(0,o.yg)("a",{parentName:"p",href:"/docs/5.0/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/5.0/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.yg)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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")))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2156],{19365:(e,n,t)=>{t.d(n,{A:()=>r});var a=t(96540),o=t(20053);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.A)(i.tabItem,r),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>A});var a=t(58168),o=t(96540),i=t(20053),r=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.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:o}}=e;return{value:n,label:t,attributes:a,default:o}}))}function d(e){const{values:n,children:t}=e;return(0,o.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 y(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,l.W6)(),i=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.aZ)(i),(0,o.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.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(!y({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:i}))),[u,s]=h({queryString:t,groupId:a}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,o.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),m=(()=>{const e=u??p;return y({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{m&&l(m)}),[m]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!y({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(p(n),u(a))},y=e=>{let n=null;switch(e.key){case"Enter":d(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 o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:r}=e;return o.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:y,onClick:d},r,{className:(0,i.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===n})}),t??n)})))}function T(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,o.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=g(e);return o.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},o.createElement(b,(0,a.A)({},e,n)),o.createElement(T,(0,a.A)({},e,n)))}function A(e){const n=(0,m.A)();return o.createElement(v,(0,a.A)({key:String(n)},e))}},38556:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>h,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=t(58168),o=(t(96540),t(15680)),i=(t(67443),t(11470)),r=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:n,...t}=e;return(0,o.yg)(y,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.yg)("p",null,"For instance:"),(0,o.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,o.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.yg)("p",null,"GraphQLite allows you to use a ",(0,o.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!")," The ",(0,o.yg)("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.yg)("br",null),(0,o.yg)("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.yg)("p",null,"In methods with a ",(0,o.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.yg)("h2",{id:"sourcefield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.yg)("p",null,"If you don't want to rewrite all ",(0,o.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.yg)("p",null,"You can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("h2",{id:"magicfield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"You can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"Any annotations described in the ",(0,o.yg)("a",{parentName:"p",href:"/docs/5.0/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/5.0/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.yg)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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")))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4d68b066.70c9c17d.js b/assets/js/4d68b066.60b726ef.js similarity index 98% rename from assets/js/4d68b066.70c9c17d.js rename to assets/js/4d68b066.60b726ef.js index 1fbfae39a..a0ee4da6b 100644 --- a/assets/js/4d68b066.70c9c17d.js +++ b/assets/js/4d68b066.60b726ef.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1443],{35927:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},u="wrapper";function d(e){let{components:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental"),"\nand their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"li"},"composer.json"),", target a major version:",(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"li"},"composer.json"),", target a minor version:",(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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([[1443],{35927:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},u="wrapper";function d(e){let{components:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental"),"\nand their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"li"},"composer.json"),", target a major version:",(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"li"},"composer.json"),", target a minor version:",(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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/4dd5816e.f6f4f160.js b/assets/js/4dd5816e.64ab8a1d.js similarity index 99% rename from assets/js/4dd5816e.f6f4f160.js rename to assets/js/4dd5816e.64ab8a1d.js index ae0e7f52a..82a43e1a6 100644 --- a/assets/js/4dd5816e.f6f4f160.js +++ b/assets/js/4dd5816e.64ab8a1d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1604],{19365:(e,a,t)=>{t.d(a,{A:()=>l});var n=t(96540),r=t(20053);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:a,hidden:t,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(o.tabItem,l),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),o=t(20053),l=t(23104),i=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function g(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function d(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,i.W6)(),o=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(o),(0,r.useCallback)((e=>{if(!o)return;const a=new URLSearchParams(n.location.search);a.set(o,e),n.replace({...n.location,search:a.toString()})}),[o,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,o=g(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!d({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:o}))),[s,u]=y({queryString:t,groupId:n}),[c,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,o]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:a,block:t,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.a_)(),g=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==i&&(c(a),s(n))},d=e=>{let a=null;switch(e.key){case"Enter":g(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:l}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:i===a?0:-1,"aria-selected":i===a,key:a,ref:e=>p.push(e),onKeyDown:d,onClick:g},l,{className:(0,o.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":i===a})}),t??a)})))}function v(e){let{lazy:a,children:t,selectedValue:n}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function N(e){const a=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,a)),r.createElement(v,(0,n.A)({},e,a)))}function T(e){const a=(0,m.A)();return r.createElement(N,(0,n.A)({key:String(a)},e))}},70758:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),o=(t(67443),t(11470)),l=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:c},d="wrapper";function y(e){let{components:a,...t}=e;return(0,r.yg)(d,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"If the ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/authentication-authorization#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.yg)("li",{parentName:"ul"},"...")),(0,r.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.yg)("code",null,"@Security")," annotation and Symfony's ",(0,r.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.yg)("h2",{id:"the-is_granted-function"},"The ",(0,r.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.yg)("p",null,"is similar to"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.yg)("p",null,"In addition, the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/authentication-authorization#not-throwing-errors"},(0,r.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"You cannot use the ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.yg)("p",null,"If you are using Laravel, you will ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.yg)("p",null,"If you are using another framework, you need to know that the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1604],{19365:(e,a,t)=>{t.d(a,{A:()=>l});var n=t(96540),r=t(20053);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:a,hidden:t,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(o.tabItem,l),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),o=t(20053),l=t(23104),i=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function g(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function d(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,i.W6)(),o=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(o),(0,r.useCallback)((e=>{if(!o)return;const a=new URLSearchParams(n.location.search);a.set(o,e),n.replace({...n.location,search:a.toString()})}),[o,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,o=g(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!d({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:o}))),[s,u]=y({queryString:t,groupId:n}),[c,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,o]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:a,block:t,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.a_)(),g=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==i&&(c(a),s(n))},d=e=>{let a=null;switch(e.key){case"Enter":g(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:l}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:i===a?0:-1,"aria-selected":i===a,key:a,ref:e=>p.push(e),onKeyDown:d,onClick:g},l,{className:(0,o.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":i===a})}),t??a)})))}function v(e){let{lazy:a,children:t,selectedValue:n}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function N(e){const a=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,a)),r.createElement(v,(0,n.A)({},e,a)))}function T(e){const a=(0,m.A)();return r.createElement(N,(0,n.A)({key:String(a)},e))}},70758:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),o=(t(67443),t(11470)),l=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:c},d="wrapper";function y(e){let{components:a,...t}=e;return(0,r.yg)(d,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"If the ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/authentication-authorization#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.yg)("li",{parentName:"ul"},"...")),(0,r.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.yg)("code",null,"@Security")," annotation and Symfony's ",(0,r.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.yg)("h2",{id:"the-is_granted-function"},"The ",(0,r.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.yg)("p",null,"is similar to"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.yg)("p",null,"In addition, the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/authentication-authorization#not-throwing-errors"},(0,r.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"You cannot use the ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.yg)("p",null,"If you are using Laravel, you will ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.yg)("p",null,"If you are using another framework, you need to know that the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4dfeb783.8925d06c.js b/assets/js/4dfeb783.89bb581b.js similarity index 99% rename from assets/js/4dfeb783.8925d06c.js rename to assets/js/4dfeb783.89bb581b.js index 89e2147e2..21da3e115 100644 --- a/assets/js/4dfeb783.8925d06c.js +++ b/assets/js/4dfeb783.89bb581b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1126],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),l=a(20053);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.A)(u.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>P});var n=a(58168),l=a(96540),u=a(20053),r=a(23104),i=a(56347),o=a(57485),p=a(31682),s=a(89466);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:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function d(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,p.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=d(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(!y({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]=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,u]=(0,s.Dv)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),g=(()=>{const e=o??c;return y({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),h(e)}),[p,h,u]),tabValues:u}}var g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),d=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(c(t),o(n))},y=e=>{let t=null;switch(e.key){case"Enter":d(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.A)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.A)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},r,{className:(0,u.A)("tabs__item",f.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 T(e){const t=h(e);return l.createElement("div",{className:(0,u.A)("tabs-container",f.tabList)},l.createElement(b,(0,n.A)({},e,t)),l.createElement(v,(0,n.A)({},e,t)))}function P(e){const t=(0,g.A)();return l.createElement(T,(0,n.A)({key:String(t)},e))}},10149:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>m,frontMatter:()=>i,metadata:()=>p,toc:()=>c});var n=a(58168),l=(a(96540),a(15680)),u=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},c=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:c},y="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/external-type-declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("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.yg)("p",null,"So instead of writing:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.yg)("p",null,"you will write:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1126],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),l=a(20053);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.A)(u.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>P});var n=a(58168),l=a(96540),u=a(20053),r=a(23104),i=a(56347),o=a(57485),p=a(31682),s=a(89466);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:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function d(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,p.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=d(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(!y({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]=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,u]=(0,s.Dv)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),g=(()=>{const e=o??c;return y({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),h(e)}),[p,h,u]),tabValues:u}}var g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),d=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(c(t),o(n))},y=e=>{let t=null;switch(e.key){case"Enter":d(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.A)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.A)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},r,{className:(0,u.A)("tabs__item",f.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 T(e){const t=h(e);return l.createElement("div",{className:(0,u.A)("tabs-container",f.tabList)},l.createElement(b,(0,n.A)({},e,t)),l.createElement(v,(0,n.A)({},e,t)))}function P(e){const t=(0,g.A)();return l.createElement(T,(0,n.A)({key:String(t)},e))}},10149:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>m,frontMatter:()=>i,metadata:()=>p,toc:()=>c});var n=a(58168),l=(a(96540),a(15680)),u=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},c=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:c},y="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.3/external-type-declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("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.yg)("p",null,"So instead of writing:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.yg)("p",null,"you will write:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4e1a0951.21082f6b.js b/assets/js/4e1a0951.99886c87.js similarity index 99% rename from assets/js/4e1a0951.21082f6b.js rename to assets/js/4e1a0951.99886c87.js index 8d0923a03..37da21de7 100644 --- a/assets/js/4e1a0951.21082f6b.js +++ b/assets/js/4e1a0951.99886c87.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4843],{19365:(e,a,n)=>{n.d(a,{A:()=>i});var t=n(96540),r=n(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:a,hidden:n,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:n},a)}},11470:(e,a,n)=>{n.d(a,{A:()=>P});var t=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),p=n(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:n,attributes:t,default:r}}=e;return{value:a,label:n,attributes:t,default:r}}))}function d(e){const{values:a,children:n}=e;return(0,r.useMemo)((()=>{const e=a??c(n);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,n])}function g(e){let{value:a,tabValues:n}=e;return n.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:n}=e;const t=(0,o.W6)(),l=function(e){let{queryString:a=!1,groupId:n}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:n});return[(0,s.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(t.location.search);a.set(l,e),t.replace({...t.location,search:a.toString()})}),[l,t])]}function m(e){const{defaultValue:a,queryString:n=!1,groupId:t}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const t=n.find((e=>e.default))??n[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:a,tabValues:l}))),[s,u]=h({queryString:n,groupId:t}),[c,m]=function(e){let{groupId:a}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(a),[t,l]=(0,p.Dv)(n);return[t,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:t}),y=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,l]),tabValues:l}}var y=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const a=e.currentTarget,n=p.indexOf(a),t=u[n].value;t!==o&&(c(a),s(t))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;a=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;a=p[n]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":n},a)},u.map((e=>{let{value:a,label:n,attributes:i}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===a})}),n??a)})))}function b(e){let{lazy:a,children:n,selectedValue:t}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(a){const e=l.find((e=>e.props.value===t));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==t}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(v,(0,t.A)({},e,a)),r.createElement(b,(0,t.A)({},e,a)))}function P(e){const a=(0,y.A)();return r.createElement(w,(0,t.A)({key:String(a)},e))}},46224:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var t=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function h(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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([[4843],{19365:(e,a,n)=>{n.d(a,{A:()=>i});var t=n(96540),r=n(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:a,hidden:n,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:n},a)}},11470:(e,a,n)=>{n.d(a,{A:()=>P});var t=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),p=n(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:n,attributes:t,default:r}}=e;return{value:a,label:n,attributes:t,default:r}}))}function d(e){const{values:a,children:n}=e;return(0,r.useMemo)((()=>{const e=a??c(n);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,n])}function g(e){let{value:a,tabValues:n}=e;return n.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:n}=e;const t=(0,o.W6)(),l=function(e){let{queryString:a=!1,groupId:n}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:n});return[(0,s.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(t.location.search);a.set(l,e),t.replace({...t.location,search:a.toString()})}),[l,t])]}function m(e){const{defaultValue:a,queryString:n=!1,groupId:t}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const t=n.find((e=>e.default))??n[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:a,tabValues:l}))),[s,u]=h({queryString:n,groupId:t}),[c,m]=function(e){let{groupId:a}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(a),[t,l]=(0,p.Dv)(n);return[t,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:t}),y=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,l]),tabValues:l}}var y=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const a=e.currentTarget,n=p.indexOf(a),t=u[n].value;t!==o&&(c(a),s(t))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;a=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;a=p[n]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":n},a)},u.map((e=>{let{value:a,label:n,attributes:i}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===a})}),n??a)})))}function b(e){let{lazy:a,children:n,selectedValue:t}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(a){const e=l.find((e=>e.props.value===t));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==t}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(v,(0,t.A)({},e,a)),r.createElement(b,(0,t.A)({},e,a)))}function P(e){const a=(0,y.A)();return r.createElement(w,(0,t.A)({key:String(a)},e))}},46224:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var t=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function h(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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/4e73bd72.b7b1e3e0.js b/assets/js/4e73bd72.9eff4f50.js similarity index 96% rename from assets/js/4e73bd72.b7b1e3e0.js rename to assets/js/4e73bd72.9eff4f50.js index 2090291c0..f387292d7 100644 --- a/assets/js/4e73bd72.b7b1e3e0.js +++ b/assets/js/4e73bd72.9eff4f50.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4981],{34027:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>c,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,a.A)({},l,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, mutations are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/3.0/queries"},"like queries"),"."),(0,i.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("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([[4981],{34027:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>c,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,a.A)({},l,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, mutations are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/3.0/queries"},"like queries"),"."),(0,i.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("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/4ed8ec4c.edc2fc06.js b/assets/js/4ed8ec4c.bc014f19.js similarity index 99% rename from assets/js/4ed8ec4c.edc2fc06.js rename to assets/js/4ed8ec4c.bc014f19.js index c5a73cc02..69c8c067b 100644 --- a/assets/js/4ed8ec4c.edc2fc06.js +++ b/assets/js/4ed8ec4c.bc014f19.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6205],{68888:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>p,toc:()=>y});var n=a(58168),r=(a(96540),a(15680));a(67443);const l={id:"annotations-reference",title:"Attributes reference",sidebar_label:"Attributes reference"},i=void 0,p={unversionedId:"annotations-reference",id:"version-8.0.0/annotations-reference",title:"Attributes reference",description:"Note: all annotations are available in PHP 8 attribute format (#[Query]), support of Doctrine annotation format was dropped.",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/annotations-reference.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"annotations-reference",title:"Attributes reference",sidebar_label:"Attributes reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/semver"}},g={},y=[{value:"#Query",id:"query",level:2},{value:"#Mutation",id:"mutation",level:2},{value:"#Subscription",id:"subscription",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}],o={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},o,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Note: all annotations are available in PHP 8 attribute format (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),"), support of Doctrine annotation format was dropped.\nSee ",(0,r.yg)("a",{parentName:"p",href:"/docs/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,r.yg)("h2",{id:"query"},"#","[Query]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]")," attribute is used to declare a GraphQL query."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,r.yg)("h2",{id:"mutation"},"#","[Mutation]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," attribute is used to declare a GraphQL mutation."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,r.yg)("h2",{id:"subscription"},"#","[Subscription]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute is used to declare a GraphQL subscription."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the subscription. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Defines the GraphQL output type that will be sent for the subscription.")))),(0,r.yg)("h2",{id:"type"},"#","[Type]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute 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,r.yg)("a",{parentName:"p",href:"#input-annotation"},"#[Input] attribute")," directly on the input type or a ",(0,r.yg)("a",{parentName:"p",href:"#factory-annotation"},"#[Factory] attribute")," to make/return an input type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"class"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("em",{parentName:"td"},"is passed"),", ",(0,r.yg)("a",{parentName:"td",href:"/docs/external-type-declaration"},"the class/enum annotated with ",(0,r.yg)("inlineCode",{parentName:"a"},"#[Type]")," becomes a service"),".")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"default"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,r.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"external"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,r.yg)("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,r.yg)("h2",{id:"extendtype"},"#","[ExtendType]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute is used to add fields to an existing GraphQL object type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"class"),(0,r.yg)("td",{parentName:"tr",align:null},"see below"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,r.yg)("a",{parentName:"td",href:"/docs/extend-type"},"The class annotated with ",(0,r.yg)("inlineCode",{parentName:"a"},"#[ExtendType]")," is a service"),".")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},"see below"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,r.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,r.yg)("h2",{id:"input"},"#","[Input]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute is used to declare a GraphQL input type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"default"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,r.yg)("inlineCode",{parentName:"td"},"true")," ",(0,r.yg)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,r.yg)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,r.yg)("inlineCode",{parentName:"td"},"true")," when ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," is used.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"update"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,r.yg)("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/subscription. This primarily applies to nullable fields.")))),(0,r.yg)("h2",{id:"field"},"#","[Field]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute is used to declare a GraphQL field."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," or ",(0,r.yg)("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,r.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,r.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,r.yg)("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,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"for"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string, array"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/input-types"},"inputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,r.yg)("h2",{id:"sourcefield"},"#","[SourceField]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," attribute is used to declare a GraphQL field."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"phpType"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"annotations"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"array\\"),(0,r.yg)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "#',"[Logged]",'" or "#',"[Right]",'" attribute as class here.')))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Note"),": ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,r.yg)("h2",{id:"magicfield"},"#","[MagicField]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[MagicField]")," attribute is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,r.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no"),"(*)"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"phpType"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no"),"(*)"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"annotations"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"array\\"),(0,r.yg)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "#',"[Logged]",'" or "#',"[Right]",'" attribute as class here.')))),(0,r.yg)("p",null,"(*) ",(0,r.yg)("strong",{parentName:"p"},"Note"),": ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,r.yg)("h2",{id:"prefetch"},"#","[Prefetch]"),(0,r.yg)("p",null,"Marks field parameter to be used for ",(0,r.yg)("a",{parentName:"p",href:"/docs/prefetch-method"},"prefetching"),"."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": parameters of methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"callable"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"callable"),(0,r.yg)("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,r.yg)("h2",{id:"logged"},"#","[Logged]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," attribute is used to declare a Query/Mutation/Field is only visible to logged users."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("p",null,"This attribute allows no arguments."),(0,r.yg)("h2",{id:"right"},"#","[Right]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attribute is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,r.yg)("h2",{id:"failwith"},"#","[FailWith]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," attribute is used to declare a default value to return in the user is not authorized to see a specific\nquery/mutation/subscription/field (according to the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes)."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," and one of ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"value"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"mixed"),(0,r.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,r.yg)("h2",{id:"hideifunauthorized"},"#","[HideIfUnauthorized]"),(0,r.yg)("div",{class:"alert alert--warning"},"This attribute 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,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[HideIfUnauthorized]")," attribute is used to completely hide the query/mutation/subscription/field if the user is not authorized\nto access it (according to the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes)."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," and one of ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"#[HideIfUnauthorized]")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," are mutually exclusive."),(0,r.yg)("h2",{id:"injectuser"},"#","[InjectUser]"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[InjectUser]")," attribute to inject an instance of the current user logged in into a parameter of your\nquery/mutation/subscription/field."),(0,r.yg)("p",null,"See ",(0,r.yg)("a",{parentName:"p",href:"/docs/authentication-authorization"},"the authentication and authorization page")," for more details."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,r.yg)("h2",{id:"security"},"#","[Security]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute 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,r.yg)("p",null,"See ",(0,r.yg)("a",{parentName:"p",href:"/docs/fine-grained-security"},"the fine grained security page")," for more details."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"default")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,r.yg)("h2",{id:"factory"},"#","[Factory]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Factory]")," attribute is used to declare a factory that turns GraphQL input types into objects."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"default"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"If ",(0,r.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,r.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,r.yg)("a",{parentName:"td",href:"/docs/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,r.yg)("inlineCode",{parentName:"a"},"#[Parameter]")," attribute"),".")))),(0,r.yg)("h2",{id:"useinputtype"},"#","[UseInputType]"),(0,r.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"inputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,r.yg)("h2",{id:"decorate"},"#","[Decorate]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Decorate]")," attribute is used ",(0,r.yg)("a",{parentName:"p",href:"/docs/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,r.yg)("inlineCode",{parentName:"a"},"#[Factory]")," attribute"),"."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,r.yg)("h2",{id:"autowire"},"#","[Autowire]"),(0,r.yg)("p",null,(0,r.yg)("a",{parentName:"p",href:"/docs/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,r.yg)("p",null,"Useful to inject services directly into ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," method arguments."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"identifier")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("h2",{id:"hideparameter"},"#","[HideParameter]"),(0,r.yg)("p",null,"Removes ",(0,r.yg)("a",{parentName:"p",href:"/docs/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,r.yg)("h2",{id:"cost"},"#","[Cost]"),(0,r.yg)("p",null,"Sets complexity and multipliers on fields for ",(0,r.yg)("a",{parentName:"p",href:"/docs/operation-complexity#static-request-analysis"},"automatic query complexity"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"complexity")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"int"),(0,r.yg)("td",{parentName:"tr",align:null},"Complexity for that field")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"multipliers")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"array\\"),(0,r.yg)("td",{parentName:"tr",align:null},"Names of fields by value of which complexity will be multiplied")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"defaultMultiplier")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"int"),(0,r.yg)("td",{parentName:"tr",align:null},"Default multiplier value if all multipliers are missing/null")))),(0,r.yg)("h2",{id:"validate"},"#","[Validate]"),(0,r.yg)("div",{class:"alert alert--info"},"This attribute is only available in the GraphQLite Laravel package"),(0,r.yg)("p",null,(0,r.yg)("a",{parentName:"p",href:"/docs/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Factory]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Decorator]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"rule")),(0,r.yg)("td",{parentName:"tr",align:null},"*yes"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,r.yg)("p",null,"Sample:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Validate(for: "$email", rule: "email|unique:users")]\n')),(0,r.yg)("h2",{id:"assertion"},"#","[Assertion]"),(0,r.yg)("p",null,(0,r.yg)("a",{parentName:"p",href:"/docs/validation"},"Validates a user input"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Assertion]")," attribute is available in the ",(0,r.yg)("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,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Factory]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Decorator]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"constraint")),(0,r.yg)("td",{parentName:"tr",align:null},"*yes"),(0,r.yg)("td",{parentName:"tr",align:null},"annotation"),(0,r.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation attributes.")))),(0,r.yg)("h2",{id:"enumtype"},(0,r.yg)("del",{parentName:"h2"},"@EnumType")),(0,r.yg)("p",null,(0,r.yg)("em",{parentName:"p"},"Deprecated: Use ",(0,r.yg)("a",{parentName:"em",href:"https://www.php.net/manual/en/language.types.enumerations.php"},"PHP 8.1's native Enums")," instead with a ",(0,r.yg)("a",{parentName:"em",href:"#type-annotation"},"#[Type]"),".")),(0,r.yg)("p",null,"The ",(0,r.yg)("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,r.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,r.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6205],{68888:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>p,toc:()=>y});var n=a(58168),r=(a(96540),a(15680));a(67443);const l={id:"annotations-reference",title:"Attributes reference",sidebar_label:"Attributes reference"},i=void 0,p={unversionedId:"annotations-reference",id:"version-8.0.0/annotations-reference",title:"Attributes reference",description:"Note: all annotations are available in PHP 8 attribute format (#[Query]), support of Doctrine annotation format was dropped.",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/annotations-reference.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"annotations-reference",title:"Attributes reference",sidebar_label:"Attributes reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/semver"}},g={},y=[{value:"#Query",id:"query",level:2},{value:"#Mutation",id:"mutation",level:2},{value:"#Subscription",id:"subscription",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}],o={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},o,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Note: all annotations are available in PHP 8 attribute format (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),"), support of Doctrine annotation format was dropped.\nSee ",(0,r.yg)("a",{parentName:"p",href:"/docs/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,r.yg)("h2",{id:"query"},"#","[Query]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]")," attribute is used to declare a GraphQL query."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,r.yg)("h2",{id:"mutation"},"#","[Mutation]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," attribute is used to declare a GraphQL mutation."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,r.yg)("h2",{id:"subscription"},"#","[Subscription]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute is used to declare a GraphQL subscription."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the subscription. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Defines the GraphQL output type that will be sent for the subscription.")))),(0,r.yg)("h2",{id:"type"},"#","[Type]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute 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,r.yg)("a",{parentName:"p",href:"#input-annotation"},"#[Input] attribute")," directly on the input type or a ",(0,r.yg)("a",{parentName:"p",href:"#factory-annotation"},"#[Factory] attribute")," to make/return an input type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"class"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("em",{parentName:"td"},"is passed"),", ",(0,r.yg)("a",{parentName:"td",href:"/docs/external-type-declaration"},"the class/enum annotated with ",(0,r.yg)("inlineCode",{parentName:"a"},"#[Type]")," becomes a service"),".")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"default"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,r.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"external"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,r.yg)("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,r.yg)("h2",{id:"extendtype"},"#","[ExtendType]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute is used to add fields to an existing GraphQL object type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"class"),(0,r.yg)("td",{parentName:"tr",align:null},"see below"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,r.yg)("a",{parentName:"td",href:"/docs/extend-type"},"The class annotated with ",(0,r.yg)("inlineCode",{parentName:"a"},"#[ExtendType]")," is a service"),".")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},"see below"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,r.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,r.yg)("h2",{id:"input"},"#","[Input]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute is used to declare a GraphQL input type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"default"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,r.yg)("inlineCode",{parentName:"td"},"true")," ",(0,r.yg)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,r.yg)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,r.yg)("inlineCode",{parentName:"td"},"true")," when ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," is used.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"update"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,r.yg)("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/subscription. This primarily applies to nullable fields.")))),(0,r.yg)("h2",{id:"field"},"#","[Field]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute is used to declare a GraphQL field."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," or ",(0,r.yg)("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,r.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,r.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,r.yg)("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,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"for"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string, array"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/input-types"},"inputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,r.yg)("h2",{id:"sourcefield"},"#","[SourceField]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," attribute is used to declare a GraphQL field."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"phpType"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"annotations"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"array\\"),(0,r.yg)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "#',"[Logged]",'" or "#',"[Right]",'" attribute as class here.')))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Note"),": ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,r.yg)("h2",{id:"magicfield"},"#","[MagicField]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[MagicField]")," attribute is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,r.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no"),"(*)"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"phpType"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no"),"(*)"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"annotations"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"array\\"),(0,r.yg)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "#',"[Logged]",'" or "#',"[Right]",'" attribute as class here.')))),(0,r.yg)("p",null,"(*) ",(0,r.yg)("strong",{parentName:"p"},"Note"),": ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,r.yg)("h2",{id:"prefetch"},"#","[Prefetch]"),(0,r.yg)("p",null,"Marks field parameter to be used for ",(0,r.yg)("a",{parentName:"p",href:"/docs/prefetch-method"},"prefetching"),"."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": parameters of methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"callable"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"callable"),(0,r.yg)("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,r.yg)("h2",{id:"logged"},"#","[Logged]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," attribute is used to declare a Query/Mutation/Field is only visible to logged users."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("p",null,"This attribute allows no arguments."),(0,r.yg)("h2",{id:"right"},"#","[Right]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attribute is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,r.yg)("h2",{id:"failwith"},"#","[FailWith]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," attribute is used to declare a default value to return in the user is not authorized to see a specific\nquery/mutation/subscription/field (according to the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes)."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," and one of ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"value"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"mixed"),(0,r.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,r.yg)("h2",{id:"hideifunauthorized"},"#","[HideIfUnauthorized]"),(0,r.yg)("div",{class:"alert alert--warning"},"This attribute 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,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[HideIfUnauthorized]")," attribute is used to completely hide the query/mutation/subscription/field if the user is not authorized\nto access it (according to the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes)."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," and one of ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"#[HideIfUnauthorized]")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," are mutually exclusive."),(0,r.yg)("h2",{id:"injectuser"},"#","[InjectUser]"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[InjectUser]")," attribute to inject an instance of the current user logged in into a parameter of your\nquery/mutation/subscription/field."),(0,r.yg)("p",null,"See ",(0,r.yg)("a",{parentName:"p",href:"/docs/authentication-authorization"},"the authentication and authorization page")," for more details."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,r.yg)("h2",{id:"security"},"#","[Security]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute 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,r.yg)("p",null,"See ",(0,r.yg)("a",{parentName:"p",href:"/docs/fine-grained-security"},"the fine grained security page")," for more details."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"default")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,r.yg)("h2",{id:"factory"},"#","[Factory]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Factory]")," attribute is used to declare a factory that turns GraphQL input types into objects."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"default"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"If ",(0,r.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,r.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,r.yg)("a",{parentName:"td",href:"/docs/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,r.yg)("inlineCode",{parentName:"a"},"#[Parameter]")," attribute"),".")))),(0,r.yg)("h2",{id:"useinputtype"},"#","[UseInputType]"),(0,r.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"inputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,r.yg)("h2",{id:"decorate"},"#","[Decorate]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Decorate]")," attribute is used ",(0,r.yg)("a",{parentName:"p",href:"/docs/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,r.yg)("inlineCode",{parentName:"a"},"#[Factory]")," attribute"),"."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,r.yg)("h2",{id:"autowire"},"#","[Autowire]"),(0,r.yg)("p",null,(0,r.yg)("a",{parentName:"p",href:"/docs/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,r.yg)("p",null,"Useful to inject services directly into ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," method arguments."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"identifier")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("h2",{id:"hideparameter"},"#","[HideParameter]"),(0,r.yg)("p",null,"Removes ",(0,r.yg)("a",{parentName:"p",href:"/docs/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,r.yg)("h2",{id:"cost"},"#","[Cost]"),(0,r.yg)("p",null,"Sets complexity and multipliers on fields for ",(0,r.yg)("a",{parentName:"p",href:"/docs/operation-complexity#static-request-analysis"},"automatic query complexity"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"complexity")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"int"),(0,r.yg)("td",{parentName:"tr",align:null},"Complexity for that field")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"multipliers")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"array\\"),(0,r.yg)("td",{parentName:"tr",align:null},"Names of fields by value of which complexity will be multiplied")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"defaultMultiplier")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"int"),(0,r.yg)("td",{parentName:"tr",align:null},"Default multiplier value if all multipliers are missing/null")))),(0,r.yg)("h2",{id:"validate"},"#","[Validate]"),(0,r.yg)("div",{class:"alert alert--info"},"This attribute is only available in the GraphQLite Laravel package"),(0,r.yg)("p",null,(0,r.yg)("a",{parentName:"p",href:"/docs/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Factory]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Decorator]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"rule")),(0,r.yg)("td",{parentName:"tr",align:null},"*yes"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,r.yg)("p",null,"Sample:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Validate(for: "$email", rule: "email|unique:users")]\n')),(0,r.yg)("h2",{id:"assertion"},"#","[Assertion]"),(0,r.yg)("p",null,(0,r.yg)("a",{parentName:"p",href:"/docs/validation"},"Validates a user input"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Assertion]")," attribute is available in the ",(0,r.yg)("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,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Factory]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Decorator]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"constraint")),(0,r.yg)("td",{parentName:"tr",align:null},"*yes"),(0,r.yg)("td",{parentName:"tr",align:null},"annotation"),(0,r.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation attributes.")))),(0,r.yg)("h2",{id:"enumtype"},(0,r.yg)("del",{parentName:"h2"},"@EnumType")),(0,r.yg)("p",null,(0,r.yg)("em",{parentName:"p"},"Deprecated: Use ",(0,r.yg)("a",{parentName:"em",href:"https://www.php.net/manual/en/language.types.enumerations.php"},"PHP 8.1's native Enums")," instead with a ",(0,r.yg)("a",{parentName:"em",href:"#type-annotation"},"#[Type]"),".")),(0,r.yg)("p",null,"The ",(0,r.yg)("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,r.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,r.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4f30448a.a01184e8.js b/assets/js/4f30448a.f6dce50e.js similarity index 99% rename from assets/js/4f30448a.a01184e8.js rename to assets/js/4f30448a.f6dce50e.js index 86cc3d6bb..a47d53b04 100644 --- a/assets/js/4f30448a.a01184e8.js +++ b/assets/js/4f30448a.f6dce50e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9581],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>v});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),u=t(31682),c=t(89466);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.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),y(e)}),[u,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),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.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({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.A)("tabs__item",f.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=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function v(e){const n=(0,m.A)();return a.createElement(w,(0,r.A)({key:String(n)},e))}},39077:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(58168),a=(t(96540),t(15680)),o=(t(67443),t(11470)),i=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,a.yg)(d,(0,r.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/3.0/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/3.0/laravel-package"},"Laravel"),")."),(0,a.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9581],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>v});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),u=t(31682),c=t(89466);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.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),y(e)}),[u,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),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.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({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.A)("tabs__item",f.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=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function v(e){const n=(0,m.A)();return a.createElement(w,(0,r.A)({key:String(n)},e))}},39077:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=t(58168),a=(t(96540),t(15680)),o=(t(67443),t(11470)),i=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,a.yg)(d,(0,r.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/3.0/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/3.0/laravel-package"},"Laravel"),")."),(0,a.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4f4b6633.de97890f.js b/assets/js/4f4b6633.efc72abb.js similarity index 99% rename from assets/js/4f4b6633.de97890f.js rename to assets/js/4f4b6633.efc72abb.js index ba85f3e13..8bd99dcd4 100644 --- a/assets/js/4f4b6633.de97890f.js +++ b/assets/js/4f4b6633.efc72abb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2589],{19365:(e,n,a)=>{a.d(n,{A:()=>r});var t=a(96540),p=a(20053);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:a,className:r}=e;return t.createElement("div",{role:"tabpanel",className:(0,p.A)(l.tabItem,r),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>N});var t=a(58168),p=a(96540),l=a(20053),r=a(23104),s=a(56347),i=a(57485),u=a(31682),o=a(89466);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:a,attributes:t,default:p}}=e;return{value:n,label:a,attributes:t,default:p}}))}function m(e){const{values:n,children:a}=e;return(0,p.useMemo)((()=>{const e=n??c(a);return function(e){const n=(0,u.X)(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,a])}function y(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,i.aZ)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function g(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!y({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[i,u]=d({queryString:a,groupId:t}),[c,g]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,p.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=i??c;return y({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{h&&s(h)}),[h]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!y({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 h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=u[a].value;t!==s&&(c(n),i(t))},y=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},u.map((e=>{let{value:n,label:a,attributes:r}=e;return p.createElement("li",(0,t.A)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:y,onClick:m},r,{className:(0,l.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function T(e){const n=g(e);return p.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},p.createElement(b,(0,t.A)({},e,n)),p.createElement(v,(0,t.A)({},e,n)))}function N(e){const n=(0,h.A)();return p.createElement(T,(0,t.A)({key:String(n)},e))}},64316:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>i,default:()=>d,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var t=a(58168),p=(a(96540),a(15680)),l=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/5.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/5.0/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"You can create a GraphQL union type ",(0,p.yg)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.yg)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.yg)("p",null,"You will first need to install ",(0,p.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("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.yg)("em",null,"type mappers")," in the ",(0,p.yg)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.yg)("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.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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([[2589],{19365:(e,n,a)=>{a.d(n,{A:()=>r});var t=a(96540),p=a(20053);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:a,className:r}=e;return t.createElement("div",{role:"tabpanel",className:(0,p.A)(l.tabItem,r),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>N});var t=a(58168),p=a(96540),l=a(20053),r=a(23104),s=a(56347),i=a(57485),u=a(31682),o=a(89466);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:a,attributes:t,default:p}}=e;return{value:n,label:a,attributes:t,default:p}}))}function m(e){const{values:n,children:a}=e;return(0,p.useMemo)((()=>{const e=n??c(a);return function(e){const n=(0,u.X)(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,a])}function y(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,i.aZ)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function g(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!y({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[i,u]=d({queryString:a,groupId:t}),[c,g]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,p.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=i??c;return y({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{h&&s(h)}),[h]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!y({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 h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=u[a].value;t!==s&&(c(n),i(t))},y=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},u.map((e=>{let{value:n,label:a,attributes:r}=e;return p.createElement("li",(0,t.A)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:y,onClick:m},r,{className:(0,l.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function T(e){const n=g(e);return p.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},p.createElement(b,(0,t.A)({},e,n)),p.createElement(v,(0,t.A)({},e,n)))}function N(e){const n=(0,h.A)();return p.createElement(T,(0,t.A)({key:String(n)},e))}},64316:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>i,default:()=>d,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var t=a(58168),p=(a(96540),a(15680)),l=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/5.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/5.0/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"You can create a GraphQL union type ",(0,p.yg)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.yg)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.yg)("p",null,"You will first need to install ",(0,p.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("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.yg)("em",null,"type mappers")," in the ",(0,p.yg)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.yg)("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.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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/4f59166d.c301b60f.js b/assets/js/4f59166d.b3fa1d46.js similarity index 99% rename from assets/js/4f59166d.c301b60f.js rename to assets/js/4f59166d.b3fa1d46.js index 108a33cd6..6f20a55f7 100644 --- a/assets/js/4f59166d.c301b60f.js +++ b/assets/js/4f59166d.b3fa1d46.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1340],{13107:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>p,toc:()=>y});var n=a(58168),l=(a(96540),a(15680));a(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/6.1/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/6.1/semver"}},g={},y=[{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}],o={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},o,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.yg)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.1/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.yg)("h2",{id:"query"},"@Query"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation"},"@Mutation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type"},"@Type"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("a",{parentName:"p",href:"#input-annotation"},"@Input annotation")," directly on the input type or a ",(0,l.yg)("a",{parentName:"p",href:"#factory-annotation"},"@Factory annoation")," to make/return an input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("em",{parentName:"td"},"is passed"),", ",(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/external-type-declaration"},"the class/enum annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," becomes a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("a",{parentName:"td",href:"/docs/6.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.yg)("h2",{id:"extendtype"},"@ExtendType"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/extend-type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"input"},"@Input"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,l.yg)("inlineCode",{parentName:"td"},"true")," ",(0,l.yg)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,l.yg)("inlineCode",{parentName:"td"},"true")," when ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"update"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.yg)("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.yg)("h2",{id:"field"},"@Field"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.yg)("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.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"for"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string, array"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/input-types"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.yg)("h2",{id:"sourcefield"},"@SourceField"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield"},"@MagicField"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"logged"},"@Logged"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right"},"@Right"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith"},"@FailWith"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"value"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized"},"@HideIfUnauthorized"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser"},"@InjectUser"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security"},"@Security"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.1/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory"},"@Factory"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype"},"@UseInputType"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate"},"@Decorate"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.1/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire"},"@Autowire"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/6.1/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter"},"@HideParameter"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.1/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"validate"},"@Validate"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/6.1/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion"},"@Assertion"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/6.1/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype"},(0,l.yg)("del",{parentName:"h2"},"@EnumType")),(0,l.yg)("p",null,(0,l.yg)("em",{parentName:"p"},"Deprecated: Use ",(0,l.yg)("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.yg)("a",{parentName:"em",href:"#type-annotation"},"@Type"),".")),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1340],{13107:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>p,toc:()=>y});var n=a(58168),l=(a(96540),a(15680));a(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/6.1/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/6.1/semver"}},g={},y=[{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}],o={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},o,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.yg)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.1/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.yg)("h2",{id:"query"},"@Query"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation"},"@Mutation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type"},"@Type"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("a",{parentName:"p",href:"#input-annotation"},"@Input annotation")," directly on the input type or a ",(0,l.yg)("a",{parentName:"p",href:"#factory-annotation"},"@Factory annoation")," to make/return an input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("em",{parentName:"td"},"is passed"),", ",(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/external-type-declaration"},"the class/enum annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," becomes a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("a",{parentName:"td",href:"/docs/6.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.yg)("h2",{id:"extendtype"},"@ExtendType"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/extend-type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"input"},"@Input"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,l.yg)("inlineCode",{parentName:"td"},"true")," ",(0,l.yg)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,l.yg)("inlineCode",{parentName:"td"},"true")," when ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"update"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.yg)("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.yg)("h2",{id:"field"},"@Field"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.yg)("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.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"for"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string, array"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/input-types"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.yg)("h2",{id:"sourcefield"},"@SourceField"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield"},"@MagicField"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"logged"},"@Logged"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right"},"@Right"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith"},"@FailWith"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"value"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized"},"@HideIfUnauthorized"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser"},"@InjectUser"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security"},"@Security"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.1/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory"},"@Factory"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("a",{parentName:"td",href:"/docs/6.1/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype"},"@UseInputType"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate"},"@Decorate"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.1/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire"},"@Autowire"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/6.1/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter"},"@HideParameter"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.1/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"validate"},"@Validate"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/6.1/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion"},"@Assertion"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/6.1/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype"},(0,l.yg)("del",{parentName:"h2"},"@EnumType")),(0,l.yg)("p",null,(0,l.yg)("em",{parentName:"p"},"Deprecated: Use ",(0,l.yg)("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.yg)("a",{parentName:"em",href:"#type-annotation"},"@Type"),".")),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4f6c3156.8d5db1a9.js b/assets/js/4f6c3156.c0232592.js similarity index 99% rename from assets/js/4f6c3156.8d5db1a9.js rename to assets/js/4f6c3156.c0232592.js index 31d110497..d5ff8dc3f 100644 --- a/assets/js/4f6c3156.8d5db1a9.js +++ b/assets/js/4f6c3156.c0232592.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3137],{60128:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>r,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>u,toc:()=>s});var a=t(58168),i=(t(96540),t(15680));t(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.1/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/6.1/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}],g={toc:s},y="wrapper";function d(e){let{components:n,...t}=e;return(0,i.yg)(y,(0,a.A)({},g,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,i.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,i.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,i.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,i.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,i.yg)("p",null,"By settings ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,i.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,i.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,i.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,i.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,i.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,i.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,i.yg)("p",null,"The mutation below will log-in a user:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,i.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,i.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,i.yg)("p",null,"In Symfony, user objects implement ",(0,i.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,i.yg)("p",null,"If you want to get more fields, just add the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"You can now query this field using an ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,i.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,i.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,i.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,i.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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")))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3137],{60128:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>r,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>u,toc:()=>s});var a=t(58168),i=(t(96540),t(15680));t(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.1/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/6.1/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}],g={toc:s},y="wrapper";function d(e){let{components:n,...t}=e;return(0,i.yg)(y,(0,a.A)({},g,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,i.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,i.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,i.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,i.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,i.yg)("p",null,"By settings ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,i.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,i.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,i.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,i.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,i.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,i.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,i.yg)("p",null,"The mutation below will log-in a user:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,i.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,i.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,i.yg)("p",null,"In Symfony, user objects implement ",(0,i.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,i.yg)("p",null,"If you want to get more fields, just add the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"You can now query this field using an ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,i.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,i.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,i.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,i.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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")))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/50122f86.0352807a.js b/assets/js/50122f86.7392e77a.js similarity index 98% rename from assets/js/50122f86.0352807a.js rename to assets/js/50122f86.7392e77a.js index f99a48153..1de94eacf 100644 --- a/assets/js/50122f86.0352807a.js +++ b/assets/js/50122f86.7392e77a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8267],{60331:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>u,toc:()=>r});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:r},y="wrapper";function d(e){let{components:n,...t}=e;return(0,i.yg)(y,(0,a.A)({},g,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,i.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,i.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,i.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,i.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,i.yg)("p",null,"By settings ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,i.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,i.yg)("p",null,"The mutation below will log-in a user:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,i.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,i.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,i.yg)("p",null,"In Symfony, user objects implement ",(0,i.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,i.yg)("p",null,"If you want to get more fields, just add the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"You can now query this field using an ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,i.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,i.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,i.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,i.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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")))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8267],{60331:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>u,toc:()=>r});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:r},y="wrapper";function d(e){let{components:n,...t}=e;return(0,i.yg)(y,(0,a.A)({},g,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,i.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,i.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,i.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,i.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,i.yg)("p",null,"By settings ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,i.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,i.yg)("p",null,"The mutation below will log-in a user:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,i.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,i.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,i.yg)("p",null,"In Symfony, user objects implement ",(0,i.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,i.yg)("p",null,"If you want to get more fields, just add the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"You can now query this field using an ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,i.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,i.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,i.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,i.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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")))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/504e6c2d.50e431dd.js b/assets/js/504e6c2d.e48c7385.js similarity index 99% rename from assets/js/504e6c2d.50e431dd.js rename to assets/js/504e6c2d.e48c7385.js index 7842e0f2c..e913bb301 100644 --- a/assets/js/504e6c2d.50e431dd.js +++ b/assets/js/504e6c2d.e48c7385.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6894],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),u=a(56347),i=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),g=(()=>{const e=i??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&u(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}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var g=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},79959:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},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.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.yg)("p",null,"You must start by installing this package:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.yg)("p",null,"In order to use this, you must first be sure that the ",(0,r.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.yg)("pre",null,(0,r.yg)("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([[6894],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),u=a(56347),i=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),g=(()=>{const e=i??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&u(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}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var g=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},79959:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},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.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.yg)("p",null,"You must start by installing this package:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.yg)("p",null,"In order to use this, you must first be sure that the ",(0,r.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.yg)("pre",null,(0,r.yg)("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.e51dcb3d.js b/assets/js/509d2004.a4a94e63.js similarity index 99% rename from assets/js/509d2004.e51dcb3d.js rename to assets/js/509d2004.a4a94e63.js index 04416abdb..9864bb809 100644 --- a/assets/js/509d2004.e51dcb3d.js +++ b/assets/js/509d2004.a4a94e63.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8457],{28570:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},m,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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([[8457],{28570:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},m,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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/51b7da58.5824a63a.js b/assets/js/51b7da58.71ef8366.js similarity index 99% rename from assets/js/51b7da58.5824a63a.js rename to assets/js/51b7da58.71ef8366.js index 7a13e0d98..b7873e9ed 100644 --- a/assets/js/51b7da58.5824a63a.js +++ b/assets/js/51b7da58.71ef8366.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7938],{10741:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>o});var t=a(58168),p=(a(96540),a(15680));a(67443);const i={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},r=void 0,s={unversionedId:"type-mapping",id:"version-8.0.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-8.0.0/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-8.0.0/type-mapping.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"docs",previous:{title:"Subscriptions",permalink:"/docs/subscriptions"},next:{title:"Autowiring services",permalink:"/docs/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:"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:"Promise mapping",id:"promise-mapping",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],u={toc:o},y="wrapper";function c(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},u,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Type]")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Field]")," attributes:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n')),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"#[Type]")," attribute on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n')),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n")),(0,p.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"Union types for return are supported in GraphQLite as of version 6.0:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"name")," property on the ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,p.yg)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,p.yg)("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.yg)("p",null,(0,p.yg)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"#[EnumType]")," attribute:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,p.yg)("pre",null,(0,p.yg)("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 /**\n * @deprecated use field `name` instead\n */\n #[Field]\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"promise-mapping"},"Promise mapping"),(0,p.yg)("p",null,"GraphQL includes a native \\GraphQL\\Deferred type.\nYou can map the return type by adding a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc.\nAn alternative to the ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement is using ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Field(outputType: SomeGQLType)]"),"."),(0,p.yg)("p",null,"All the previously mentioned mappings work with Promises, except when a return type is explicitly declared\nin the method signature."),(0,p.yg)("p",null,"This allows you to use \\Overblog\\DataLoader\\DataLoader as an alternative\nfor resolving N+1 query issues and caching intermediate results."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass Product\n{\n // ...\n\n /**\n * @return string\n */\n #[Field]\n public function getName(): Deferred\n {\n return new Deferred(fn() => $this->name);\n }\n\n #[Field(outputType: "Float")]\n public function getPrice(): Deferred\n {\n return new Deferred(fn() => $this->price);\n }\n\n #[Field(outputType: "[String!]!")]\n public function getCategories(#[Autowire(\'categoryDataLoader\')] DataLoader $categoryDataLoader): SyncPromise\n {\n return $categoryDataLoader->load($this->id)->adoptedPromise;\n }\n}\n')),(0,p.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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([[7938],{10741:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>o});var t=a(58168),p=(a(96540),a(15680));a(67443);const i={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},r=void 0,s={unversionedId:"type-mapping",id:"version-8.0.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-8.0.0/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-8.0.0/type-mapping.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"docs",previous:{title:"Subscriptions",permalink:"/docs/subscriptions"},next:{title:"Autowiring services",permalink:"/docs/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:"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:"Promise mapping",id:"promise-mapping",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],u={toc:o},y="wrapper";function c(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},u,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Type]")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Field]")," attributes:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n')),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"#[Type]")," attribute on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n')),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n")),(0,p.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"Union types for return are supported in GraphQLite as of version 6.0:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"name")," property on the ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,p.yg)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,p.yg)("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.yg)("p",null,(0,p.yg)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"#[EnumType]")," attribute:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,p.yg)("pre",null,(0,p.yg)("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 /**\n * @deprecated use field `name` instead\n */\n #[Field]\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"promise-mapping"},"Promise mapping"),(0,p.yg)("p",null,"GraphQL includes a native \\GraphQL\\Deferred type.\nYou can map the return type by adding a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc.\nAn alternative to the ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement is using ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Field(outputType: SomeGQLType)]"),"."),(0,p.yg)("p",null,"All the previously mentioned mappings work with Promises, except when a return type is explicitly declared\nin the method signature."),(0,p.yg)("p",null,"This allows you to use \\Overblog\\DataLoader\\DataLoader as an alternative\nfor resolving N+1 query issues and caching intermediate results."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass Product\n{\n // ...\n\n /**\n * @return string\n */\n #[Field]\n public function getName(): Deferred\n {\n return new Deferred(fn() => $this->name);\n }\n\n #[Field(outputType: "Float")]\n public function getPrice(): Deferred\n {\n return new Deferred(fn() => $this->price);\n }\n\n #[Field(outputType: "[String!]!")]\n public function getCategories(#[Autowire(\'categoryDataLoader\')] DataLoader $categoryDataLoader): SyncPromise\n {\n return $categoryDataLoader->load($this->id)->adoptedPromise;\n }\n}\n')),(0,p.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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/5285d58e.2b72d61e.js b/assets/js/5285d58e.6fcf2c6d.js similarity index 99% rename from assets/js/5285d58e.2b72d61e.js rename to assets/js/5285d58e.6fcf2c6d.js index ae0ad8d4c..01a3550ff 100644 --- a/assets/js/5285d58e.2b72d61e.js +++ b/assets/js/5285d58e.6fcf2c6d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5675],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),l=n(20053);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.A)(r.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>$});var a=n(58168),l=n(96540),r=n(20053),i=n(23104),o=n(56347),u=n(57485),p=n(31682),s=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function g(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.W6)(),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.aZ)(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 m(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(!y({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]=g({queryString:n,groupId:a}),[c,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Dv)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),h=(()=>{const e=u??c;return y({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),m(e)}),[p,m,r]),tabValues:r}}var h=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},y=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.A)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},i,{className:(0,r.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(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 I(e){const t=m(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,t)),l.createElement(v,(0,a.A)({},e,t)))}function $(e){const t=(0,h.A)();return l.createElement(I,(0,a.A)({key:String(t)},e))}},25529:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>g,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(58168),l=(n(96540),n(15680)),r=(n(67443),n(11470)),i=n(19365);const o={id:"input-types",title:"Input types",sidebar_label:"Input types"},u=void 0,p={unversionedId:"input-types",id:"version-7.0.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-7.0.0/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/7.0.0/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/input-types.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"docs",previous:{title:"External type declaration",permalink:"/docs/7.0.0/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/7.0.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},y="wrapper";function g(e){let{components:t,...n}=e;return(0,l.yg)(y,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.yg)("p",null,"Your GraphQL query might look like this:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,l.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,l.yg)("a",{parentName:"p",href:"#input-attribute"},(0,l.yg)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,l.yg)("a",{parentName:"p",href:"#factory"},"Factory method"),"."),(0,l.yg)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,l.yg)("p",null,"Using the ",(0,l.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"Now if you call the ",(0,l.yg)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,l.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.yg)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,l.yg)("p",null,"There are some important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},"The ",(0,l.yg)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized on properties for Input Type, as well as setters."),(0,l.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.yg)("ul",{parentName:"li"},(0,l.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,l.yg)("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.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,l.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on the setter, instead of the property, allowing you to have use many other attributes (",(0,l.yg)("inlineCode",{parentName:"li"},"Security"),", ",(0,l.yg)("inlineCode",{parentName:"li"},"Right"),", ",(0,l.yg)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,l.yg)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,l.yg)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,l.yg)("li",{parentName:"ul"},"It's advised to use the ",(0,l.yg)("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.yg)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,l.yg)("p",null,"Simple usage of the ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," class."),(0,l.yg)("p",null,"You can add multiple ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"There are 2 input types added to the ",(0,l.yg)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,l.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.yg)("p",null,"Note that ",(0,l.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.yg)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.yg)("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.yg)("h2",{id:"factory"},"Factory"),(0,l.yg)("p",null,"A ",(0,l.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.yg)("p",null,"Here is an example of factory:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.yg)("p",null,"A few important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.yg)("p",null,"You can use the ",(0,l.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.yg)("p",null,"Here is an annotated sample:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("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.yg)("p",null,"Image your ",(0,l.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"With the ",(0,l.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.yg)("p",null,"To be able to hide an argument, the argument must have a default value."))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5675],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),l=n(20053);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.A)(r.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>$});var a=n(58168),l=n(96540),r=n(20053),i=n(23104),o=n(56347),u=n(57485),p=n(31682),s=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function g(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.W6)(),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.aZ)(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 m(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(!y({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]=g({queryString:n,groupId:a}),[c,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Dv)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),h=(()=>{const e=u??c;return y({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),m(e)}),[p,m,r]),tabValues:r}}var h=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},y=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.A)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},i,{className:(0,r.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(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 I(e){const t=m(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,t)),l.createElement(v,(0,a.A)({},e,t)))}function $(e){const t=(0,h.A)();return l.createElement(I,(0,a.A)({key:String(t)},e))}},25529:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>g,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(58168),l=(n(96540),n(15680)),r=(n(67443),n(11470)),i=n(19365);const o={id:"input-types",title:"Input types",sidebar_label:"Input types"},u=void 0,p={unversionedId:"input-types",id:"version-7.0.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-7.0.0/input-types.mdx",sourceDirName:".",slug:"/input-types",permalink:"/docs/7.0.0/input-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/input-types.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"input-types",title:"Input types",sidebar_label:"Input types"},sidebar:"docs",previous:{title:"External type declaration",permalink:"/docs/7.0.0/external-type-declaration"},next:{title:"Inheritance and interfaces",permalink:"/docs/7.0.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},y="wrapper";function g(e){let{components:t,...n}=e;return(0,l.yg)(y,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.yg)("p",null,"Your GraphQL query might look like this:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,l.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,l.yg)("a",{parentName:"p",href:"#input-attribute"},(0,l.yg)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,l.yg)("a",{parentName:"p",href:"#factory"},"Factory method"),"."),(0,l.yg)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,l.yg)("p",null,"Using the ",(0,l.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"Now if you call the ",(0,l.yg)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,l.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.yg)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,l.yg)("p",null,"There are some important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},"The ",(0,l.yg)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized on properties for Input Type, as well as setters."),(0,l.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.yg)("ul",{parentName:"li"},(0,l.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,l.yg)("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.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,l.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on the setter, instead of the property, allowing you to have use many other attributes (",(0,l.yg)("inlineCode",{parentName:"li"},"Security"),", ",(0,l.yg)("inlineCode",{parentName:"li"},"Right"),", ",(0,l.yg)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,l.yg)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,l.yg)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,l.yg)("li",{parentName:"ul"},"It's advised to use the ",(0,l.yg)("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.yg)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,l.yg)("p",null,"Simple usage of the ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," class."),(0,l.yg)("p",null,"You can add multiple ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"There are 2 input types added to the ",(0,l.yg)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,l.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.yg)("p",null,"Note that ",(0,l.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.yg)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.yg)("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.yg)("h2",{id:"factory"},"Factory"),(0,l.yg)("p",null,"A ",(0,l.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.yg)("p",null,"Here is an example of factory:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.yg)("p",null,"A few important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.yg)("p",null,"You can use the ",(0,l.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.yg)("p",null,"Here is an annotated sample:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("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.yg)("p",null,"Image your ",(0,l.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"With the ",(0,l.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.yg)("p",null,"To be able to hide an argument, the argument must have a default value."))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/528fe65e.145effa3.js b/assets/js/528fe65e.8ac08875.js similarity index 99% rename from assets/js/528fe65e.145effa3.js rename to assets/js/528fe65e.8ac08875.js index fbe36aaaf..0a4cf6680 100644 --- a/assets/js/528fe65e.145effa3.js +++ b/assets/js/528fe65e.8ac08875.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1027],{65009:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>o});var t=a(58168),p=(a(96540),a(15680));a(67443);const i={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},r=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"docs",previous:{title:"Subscriptions",permalink:"/docs/next/subscriptions"},next:{title:"Autowiring services",permalink:"/docs/next/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:"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:"Promise mapping",id:"promise-mapping",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],u={toc:o},y="wrapper";function c(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},u,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/next/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Type]")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Field]")," attributes:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n')),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"#[Type]")," attribute on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n')),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/next/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n")),(0,p.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"Union types for return are supported in GraphQLite as of version 6.0:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"name")," property on the ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,p.yg)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,p.yg)("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.yg)("p",null,(0,p.yg)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"#[EnumType]")," attribute:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,p.yg)("pre",null,(0,p.yg)("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 /**\n * @deprecated use field `name` instead\n */\n #[Field]\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"promise-mapping"},"Promise mapping"),(0,p.yg)("p",null,"GraphQL includes a native \\GraphQL\\Deferred type.\nYou can map the return type by adding a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc.\nAn alternative to the ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement is using ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Field(outputType: SomeGQLType)]"),"."),(0,p.yg)("p",null,"All the previously mentioned mappings work with Promises, except when a return type is explicitly declared\nin the method signature."),(0,p.yg)("p",null,"This allows you to use \\Overblog\\DataLoader\\DataLoader as an alternative\nfor resolving N+1 query issues and caching intermediate results."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass Product\n{\n // ...\n\n /**\n * @return string\n */\n #[Field]\n public function getName(): Deferred\n {\n return new Deferred(fn() => $this->name);\n }\n\n #[Field(outputType: "Float")]\n public function getPrice(): Deferred\n {\n return new Deferred(fn() => $this->price);\n }\n\n #[Field(outputType: "[String!]!")]\n public function getCategories(#[Autowire(\'categoryDataLoader\')] DataLoader $categoryDataLoader): SyncPromise\n {\n return $categoryDataLoader->load($this->id)->adoptedPromise;\n }\n}\n')),(0,p.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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([[1027],{65009:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>o});var t=a(58168),p=(a(96540),a(15680));a(67443);const i={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},r=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"docs",previous:{title:"Subscriptions",permalink:"/docs/next/subscriptions"},next:{title:"Autowiring services",permalink:"/docs/next/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:"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:"Promise mapping",id:"promise-mapping",level:2},{value:"More scalar types",id:"more-scalar-types",level:2}],u={toc:o},y="wrapper";function c(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},u,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/next/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Type]")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Field]")," attributes:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n')),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"#[Type]")," attribute on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n')),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/next/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n")),(0,p.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"Union types for return are supported in GraphQLite as of version 6.0:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"name")," property on the ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,p.yg)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,p.yg)("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.yg)("p",null,(0,p.yg)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"#[EnumType]")," attribute:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,p.yg)("pre",null,(0,p.yg)("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 /**\n * @deprecated use field `name` instead\n */\n #[Field]\n public function getProductName(): string\n {\n return $this->name;\n }\n}\n")),(0,p.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"promise-mapping"},"Promise mapping"),(0,p.yg)("p",null,"GraphQL includes a native \\GraphQL\\Deferred type.\nYou can map the return type by adding a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc.\nAn alternative to the ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement is using ",(0,p.yg)("inlineCode",{parentName:"p"},"#[Field(outputType: SomeGQLType)]"),"."),(0,p.yg)("p",null,"All the previously mentioned mappings work with Promises, except when a return type is explicitly declared\nin the method signature."),(0,p.yg)("p",null,"This allows you to use \\Overblog\\DataLoader\\DataLoader as an alternative\nfor resolving N+1 query issues and caching intermediate results."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type]\nclass Product\n{\n // ...\n\n /**\n * @return string\n */\n #[Field]\n public function getName(): Deferred\n {\n return new Deferred(fn() => $this->name);\n }\n\n #[Field(outputType: "Float")]\n public function getPrice(): Deferred\n {\n return new Deferred(fn() => $this->price);\n }\n\n #[Field(outputType: "[String!]!")]\n public function getCategories(#[Autowire(\'categoryDataLoader\')] DataLoader $categoryDataLoader): SyncPromise\n {\n return $categoryDataLoader->load($this->id)->adoptedPromise;\n }\n}\n')),(0,p.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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/54c144e4.3cb139c7.js b/assets/js/54c144e4.dcbaa6f6.js similarity index 98% rename from assets/js/54c144e4.3cb139c7.js rename to assets/js/54c144e4.dcbaa6f6.js index a675002f1..5dc8e7c9f 100644 --- a/assets/js/54c144e4.3cb139c7.js +++ b/assets/js/54c144e4.dcbaa6f6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7735],{46368:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>r,metadata:()=>l,toc:()=>o});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.yg)("p",null,"Written in ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.yg)("p",null,"The GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.yg)("div",{class:"alert alert--warning"},"Right now, there is no way to explicitly declare a GraphQL interface using GraphQLite.",(0,i.yg)("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([[7735],{46368:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>h,frontMatter:()=>r,metadata:()=>l,toc:()=>o});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"class ContactController\n{\n /**\n * @Query()\n */\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.yg)("p",null,"Written in ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.yg)("p",null,"The GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.yg)("div",{class:"alert alert--warning"},"Right now, there is no way to explicitly declare a GraphQL interface using GraphQLite.",(0,i.yg)("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.ab787787.js b/assets/js/54ca8693.d58f5d8d.js similarity index 98% rename from assets/js/54ca8693.ab787787.js rename to assets/js/54ca8693.d58f5d8d.js index d00653436..e982a7fc2 100644 --- a/assets/js/54ca8693.ab787787.js +++ b/assets/js/54ca8693.d58f5d8d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6766],{7205:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>g,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var a=t(58168),r=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(y,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Symfony 4.x"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"The Symfony Flex recipe is not yet available."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,r.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"app/AppKernel.php")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>g,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var a=t(58168),r=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(y,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Symfony 4.x"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"The Symfony Flex recipe is not yet available."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,r.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"app/AppKernel.php")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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([[1930],{68168:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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.81deafd2.js b/assets/js/56279b5e.29c4d3ad.js similarity index 99% rename from assets/js/56279b5e.81deafd2.js rename to assets/js/56279b5e.29c4d3ad.js index c7d804273..6fe5c70fa 100644 --- a/assets/js/56279b5e.81deafd2.js +++ b/assets/js/56279b5e.29c4d3ad.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4032],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),l=n(20053);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.A)(r.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>T});var a=n(58168),l=n(96540),r=n(20053),i=n(23104),o=n(56347),u=n(57485),p=n(31682),s=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function g(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.W6)(),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.aZ)(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 m(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(!y({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]=g({queryString:n,groupId:a}),[c,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Dv)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),h=(()=>{const e=u??c;return y({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),m(e)}),[p,m,r]),tabValues:r}}var h=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},y=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.A)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},i,{className:(0,r.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(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 I(e){const t=m(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,t)),l.createElement(v,(0,a.A)({},e,t)))}function T(e){const t=(0,h.A)();return l.createElement(I,(0,a.A)({key:String(t)},e))}},32902:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>g,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(58168),l=(n(96540),n(15680)),r=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function g(e){let{components:t,...n}=e;return(0,l.yg)(y,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.yg)("p",null,"Your GraphQL query might look like this:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,l.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using ",(0,l.yg)("strong",{parentName:"p"},"Factory")," or annotating the class with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input"),"."),(0,l.yg)("h2",{id:"factory"},"Factory"),(0,l.yg)("p",null,"A ",(0,l.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.yg)("p",null,"Here is an example of factory:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.yg)("p",null,"A few important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.yg)("p",null,"You can use the ",(0,l.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.yg)("p",null,"Here is an annotated sample:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("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.yg)("p",null,"Image your ",(0,l.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"With the ",(0,l.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.yg)("p",null,"To be able to hide an argument, the argument must have a default value."),(0,l.yg)("h2",{id:"input-annotation"},"@Input Annotation"),(0,l.yg)("p",null,"Let's transform ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," class into an input type by adding ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation to it and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to corresponding properties:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"Now if you call ",(0,l.yg)("inlineCode",{parentName:"p"},"getCities()")," query you can pass the location input in the same way as with factories.\nThe ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with provided ",(0,l.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.yg)("inlineCode",{parentName:"p"},"longitude")," and passed to the controller as a parameter."),(0,l.yg)("p",null,"There are some important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized only on properties for Input Type."),(0,l.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.yg)("ul",{parentName:"li"},(0,l.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort."),(0,l.yg)("li",{parentName:"ul"},"For private or protected properties implemented public setter is required (if they are not set via constructor). For example ",(0,l.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),".")))),(0,l.yg)("h3",{id:"multiple-input-types-per-one-class"},"Multiple input types per one class"),(0,l.yg)("p",null,"Simple usage of ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"There are 2 input types created for just one class: ",(0,l.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.yg)("p",null,"Note that ",(0,l.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.yg)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.yg)("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."))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4032],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),l=n(20053);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.A)(r.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>T});var a=n(58168),l=n(96540),r=n(20053),i=n(23104),o=n(56347),u=n(57485),p=n(31682),s=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function g(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.W6)(),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.aZ)(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 m(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(!y({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]=g({queryString:n,groupId:a}),[c,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Dv)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),h=(()=>{const e=u??c;return y({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),m(e)}),[p,m,r]),tabValues:r}}var h=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},y=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.A)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},i,{className:(0,r.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(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 I(e){const t=m(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,t)),l.createElement(v,(0,a.A)({},e,t)))}function T(e){const t=(0,h.A)();return l.createElement(I,(0,a.A)({key:String(t)},e))}},32902:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>g,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(58168),l=(n(96540),n(15680)),r=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function g(e){let{components:t,...n}=e;return(0,l.yg)(y,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.yg)("p",null,"Your GraphQL query might look like this:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,l.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using ",(0,l.yg)("strong",{parentName:"p"},"Factory")," or annotating the class with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input"),"."),(0,l.yg)("h2",{id:"factory"},"Factory"),(0,l.yg)("p",null,"A ",(0,l.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.yg)("p",null,"Here is an example of factory:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.yg)("p",null,"A few important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.yg)("p",null,"You can use the ",(0,l.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.yg)("p",null,"Here is an annotated sample:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("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.yg)("p",null,"Image your ",(0,l.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"With the ",(0,l.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.yg)("p",null,"To be able to hide an argument, the argument must have a default value."),(0,l.yg)("h2",{id:"input-annotation"},"@Input Annotation"),(0,l.yg)("p",null,"Let's transform ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," class into an input type by adding ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation to it and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to corresponding properties:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"Now if you call ",(0,l.yg)("inlineCode",{parentName:"p"},"getCities()")," query you can pass the location input in the same way as with factories.\nThe ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with provided ",(0,l.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.yg)("inlineCode",{parentName:"p"},"longitude")," and passed to the controller as a parameter."),(0,l.yg)("p",null,"There are some important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized only on properties for Input Type."),(0,l.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.yg)("ul",{parentName:"li"},(0,l.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort."),(0,l.yg)("li",{parentName:"ul"},"For private or protected properties implemented public setter is required (if they are not set via constructor). For example ",(0,l.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),".")))),(0,l.yg)("h3",{id:"multiple-input-types-per-one-class"},"Multiple input types per one class"),(0,l.yg)("p",null,"Simple usage of ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"There are 2 input types created for just one class: ",(0,l.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.yg)("p",null,"Note that ",(0,l.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.yg)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.yg)("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."))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/565a5567.0caaaeb8.js b/assets/js/565a5567.d3e945b5.js similarity index 98% rename from assets/js/565a5567.0caaaeb8.js rename to assets/js/565a5567.d3e945b5.js index 330b99dab..5ea619c76 100644 --- a/assets/js/565a5567.0caaaeb8.js +++ b/assets/js/565a5567.d3e945b5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5547],{86017:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},c="wrapper";function d(t){let{components:e,...n}=t;return(0,i.yg)(c,(0,a.A)({},u,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in GraphQLite 5.0"),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,i.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"Please note that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,i.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,i.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,i.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,i.yg)("div",{class:"alert alert--info"},(0,i.yg)("strong",null,"Heads up!"),"Some IDEs provide support for Doctrine annotations:",(0,i.yg)("ul",null,(0,i.yg)("li",null,"PhpStorm via the ",(0,i.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,i.yg)("li",null,"Eclipse via the ",(0,i.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,i.yg)("li",null,"Netbeans has native support")),(0,i.yg)("p",null,"We strongly recommend using an IDE that has Doctrine annotations support.")),(0,i.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.yg)("p",null,"The same code can be written this way:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.yg)("p",null,"They support the same attributes too."),(0,i.yg)("p",null,"A few notable differences:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,i.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,i.yg)("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.yg)("p",null,"Let's take an example with the ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/autowiring"},(0,i.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"PHP 7+")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"PHP 8")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5547],{86017:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},c="wrapper";function d(t){let{components:e,...n}=t;return(0,i.yg)(c,(0,a.A)({},u,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in GraphQLite 5.0"),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,i.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"Please note that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,i.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,i.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,i.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,i.yg)("div",{class:"alert alert--info"},(0,i.yg)("strong",null,"Heads up!"),"Some IDEs provide support for Doctrine annotations:",(0,i.yg)("ul",null,(0,i.yg)("li",null,"PhpStorm via the ",(0,i.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,i.yg)("li",null,"Eclipse via the ",(0,i.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,i.yg)("li",null,"Netbeans has native support")),(0,i.yg)("p",null,"We strongly recommend using an IDE that has Doctrine annotations support.")),(0,i.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.yg)("p",null,"The same code can be written this way:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.yg)("p",null,"They support the same attributes too."),(0,i.yg)("p",null,"A few notable differences:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,i.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,i.yg)("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.yg)("p",null,"Let's take an example with the ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/autowiring"},(0,i.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"PHP 7+")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"PHP 8")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/56af72f6.da5bc172.js b/assets/js/56af72f6.73430305.js similarity index 99% rename from assets/js/56af72f6.da5bc172.js rename to assets/js/56af72f6.73430305.js index a57263f2e..c835973e6 100644 --- a/assets/js/56af72f6.da5bc172.js +++ b/assets/js/56af72f6.73430305.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4368],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),i=a(89466);function y(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??y(a);return function(e){const t=(0,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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(!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}),[y,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=s??y;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:y}=(0,o.a_)(),c=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(y(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":c(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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:c},o,{className:(0,p.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},27809:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>y});var n=a(58168),r=(a(96540),a(15680)),p=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],c={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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([[4368],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),i=a(89466);function y(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??y(a);return function(e){const t=(0,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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(!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}),[y,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=s??y;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:y}=(0,o.a_)(),c=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(y(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":c(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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:c},o,{className:(0,p.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},27809:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>y});var n=a(58168),r=(a(96540),a(15680)),p=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],c={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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.d52d4095.js b/assets/js/5792f9ba.65bfc82c.js similarity index 99% rename from assets/js/5792f9ba.d52d4095.js rename to assets/js/5792f9ba.65bfc82c.js index d6aa1f3b9..db5301c53 100644 --- a/assets/js/5792f9ba.d52d4095.js +++ b/assets/js/5792f9ba.65bfc82c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9606],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),g(e)}),[u,g,i]),tabValues:i}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function T(e){const t=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},18118:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),i=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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,...a}=e;return(0,r.yg)(h,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null," #[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null," #[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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([[9606],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),g(e)}),[u,g,i]),tabValues:i}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function T(e){const t=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},18118:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),i=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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,...a}=e;return(0,r.yg)(h,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null," #[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null," #[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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.e2729820.js b/assets/js/579cc8d4.33781386.js similarity index 98% rename from assets/js/579cc8d4.e2729820.js rename to assets/js/579cc8d4.33781386.js index 8cfe61ef9..5407b913d 100644 --- a/assets/js/579cc8d4.e2729820.js +++ b/assets/js/579cc8d4.33781386.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3610],{55365:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>g,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"}},c={},u=[],l={toc:u},h="wrapper";function g(e){let{components:t,...n}=e;return(0,r.yg)(h,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--info"},"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package"),(0,r.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/3.0/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3610],{55365:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>g,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"implementing-security",title:"Connecting GraphQLite to your framework's security module",sidebar_label:"Connecting security to your framework"}},c={},u=[],l={toc:u},h="wrapper";function g(e){let{components:t,...n}=e;return(0,r.yg)(h,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--info"},"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package"),(0,r.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/3.0/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/57f5c28c.ec3d26d8.js b/assets/js/57f5c28c.26873cdb.js similarity index 99% rename from assets/js/57f5c28c.ec3d26d8.js rename to assets/js/57f5c28c.26873cdb.js index 0fb1a194d..7f43dda7a 100644 --- a/assets/js/57f5c28c.ec3d26d8.js +++ b/assets/js/57f5c28c.26873cdb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8372],{93300:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>l,contentTitle:()=>i,default:()=>u,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var r=a(58168),t=(a(96540),a(15680));a(67443);const o={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},i=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},l={},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,t.yg)(d,(0,r.A)({},c,o,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("p",null,"If you are using ",(0,t.yg)("strong",{parentName:"p"},"Symfony 4.x"),", checkout the ",(0,t.yg)("a",{parentName:"p",href:"/docs/4.0/symfony-bundle"},"Symfony bundle"),"."),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"composer.json")),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"index.php")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/container.php")),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"src/Controllers/MyController.php")),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/container.php")),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."),(0,t.yg)("p",null,(0,t.yg)("img",{src:a(67258).A,width:"1132",height:"352"})))}u.isMDXComponent=!0},67258:(e,n,a)=>{a.d(n,{A:()=>r});const r=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8372],{93300:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>l,contentTitle:()=>i,default:()=>u,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var r=a(58168),t=(a(96540),a(15680));a(67443);const o={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},i=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},l={},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,t.yg)(d,(0,r.A)({},c,o,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("p",null,"If you are using ",(0,t.yg)("strong",{parentName:"p"},"Symfony 4.x"),", checkout the ",(0,t.yg)("a",{parentName:"p",href:"/docs/4.0/symfony-bundle"},"Symfony bundle"),"."),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"composer.json")),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"index.php")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/container.php")),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"src/Controllers/MyController.php")),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/container.php")),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."),(0,t.yg)("p",null,(0,t.yg)("img",{src:a(67258).A,width:"1132",height:"352"})))}u.isMDXComponent=!0},67258:(e,n,a)=>{a.d(n,{A:()=>r});const r=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/5881f7ec.0fc3f62b.js b/assets/js/5881f7ec.1970d743.js similarity index 99% rename from assets/js/5881f7ec.0fc3f62b.js rename to assets/js/5881f7ec.1970d743.js index 46734cd41..65b61e3af 100644 --- a/assets/js/5881f7ec.0fc3f62b.js +++ b/assets/js/5881f7ec.1970d743.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8628],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),i=a(20053);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.A)(o.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>N});var n=a(58168),i=a(96540),o=a(20053),r=a(23104),l=a(56347),s=a(57485),u=a(31682),d=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 m(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(!y({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]=h({queryString:a,groupId:n}),[p,m]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,d.Dv)(a);return[n,(0,i.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),g=(()=>{const e=s??p;return y({value:e,tabValues:o})?e:null})();(0,i.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!y({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),m(e)}),[u,m,o]),tabValues:o}}var g=a(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},y=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:r}=e;return i.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:y,onClick:c},r,{className:(0,o.A)("tabs__item",v.tabItem,r?.className,{"tabs__item--active":l===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,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 w(e){const t=m(e);return i.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},i.createElement(f,(0,n.A)({},e,t)),i.createElement(b,(0,n.A)({},e,t)))}function N(e){const t=(0,g.A)();return i.createElement(w,(0,n.A)({key:String(t)},e))}},18532:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(58168),i=(a(96540),a(15680)),o=(a(67443),a(11470)),r=a(19365);const l={id:"validation",title:"Validation",sidebar_label:"User input validation"},s=void 0,u={unversionedId:"validation",id:"version-7.0.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-7.0.0/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/7.0.0/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/validation.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"docs",previous:{title:"Error handling",permalink:"/docs/7.0.0/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/7.0.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 / subscription / factory ...",id:"using-the-validator-directly-on-a-query--mutation--subscription--factory-",level:3},{value:"Custom InputType Validation",id:"custom-inputtype-validation",level:2}],c={toc:p},y="wrapper";function h(e){let{components:t,...a}=e;return(0,i.yg)(y,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,i.yg)("a",{parentName:"p",href:"/docs/7.0.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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.yg)("pre",{parentName:"li"},(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--subscription--factory-"},"Using the validator directly on a query / mutation / subscription / factory ..."),(0,i.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,i.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.yg)("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.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.yg)("p",null,"You can also pass an array to the ",(0,i.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,i.yg)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"),(0,i.yg)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.yg)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.yg)("inlineCode",{parentName:"p"},"@Input")," annotation or PHP8 ",(0,i.yg)("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.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("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.yg)("p",null,"To get started with validation on input types defined by an ",(0,i.yg)("inlineCode",{parentName:"p"},"@Input")," annotation, you'll first need to register your validator with the ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Your input type validator must implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.yg)("p",null,"You'll notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.yg)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.yg)("p",null,"Also available is the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8628],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),i=a(20053);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.A)(o.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>N});var n=a(58168),i=a(96540),o=a(20053),r=a(23104),l=a(56347),s=a(57485),u=a(31682),d=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 m(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(!y({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]=h({queryString:a,groupId:n}),[p,m]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,d.Dv)(a);return[n,(0,i.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),g=(()=>{const e=s??p;return y({value:e,tabValues:o})?e:null})();(0,i.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!y({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),m(e)}),[u,m,o]),tabValues:o}}var g=a(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},y=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:r}=e;return i.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:y,onClick:c},r,{className:(0,o.A)("tabs__item",v.tabItem,r?.className,{"tabs__item--active":l===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,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 w(e){const t=m(e);return i.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},i.createElement(f,(0,n.A)({},e,t)),i.createElement(b,(0,n.A)({},e,t)))}function N(e){const t=(0,g.A)();return i.createElement(w,(0,n.A)({key:String(t)},e))}},18532:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=a(58168),i=(a(96540),a(15680)),o=(a(67443),a(11470)),r=a(19365);const l={id:"validation",title:"Validation",sidebar_label:"User input validation"},s=void 0,u={unversionedId:"validation",id:"version-7.0.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-7.0.0/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/7.0.0/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/validation.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"docs",previous:{title:"Error handling",permalink:"/docs/7.0.0/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/7.0.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 / subscription / factory ...",id:"using-the-validator-directly-on-a-query--mutation--subscription--factory-",level:3},{value:"Custom InputType Validation",id:"custom-inputtype-validation",level:2}],c={toc:p},y="wrapper";function h(e){let{components:t,...a}=e;return(0,i.yg)(y,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,i.yg)("a",{parentName:"p",href:"/docs/7.0.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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.yg)("pre",{parentName:"li"},(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--subscription--factory-"},"Using the validator directly on a query / mutation / subscription / factory ..."),(0,i.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,i.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.yg)("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.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.yg)("p",null,"You can also pass an array to the ",(0,i.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,i.yg)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"),(0,i.yg)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.yg)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.yg)("inlineCode",{parentName:"p"},"@Input")," annotation or PHP8 ",(0,i.yg)("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.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("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.yg)("p",null,"To get started with validation on input types defined by an ",(0,i.yg)("inlineCode",{parentName:"p"},"@Input")," annotation, you'll first need to register your validator with the ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Your input type validator must implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.yg)("p",null,"You'll notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.yg)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.yg)("p",null,"Also available is the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/58d52345.1f7e6858.js b/assets/js/58d52345.0df60a2d.js similarity index 97% rename from assets/js/58d52345.1f7e6858.js rename to assets/js/58d52345.0df60a2d.js index e6bd64a28..f10b451ce 100644 --- a/assets/js/58d52345.1f7e6858.js +++ b/assets/js/58d52345.0df60a2d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[81],{69213:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>o,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>u});var r=a(58168),n=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},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.yg)(p,(0,r.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,n.yg)("p",{align:"center"},(0,n.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,n.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,n.yg)("h2",{id:"features"},"Features"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,n.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,n.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,n.yg)("h2",{id:"basic-example"},"Basic example"),(0,n.yg)("p",null,"First, declare a query in your controller:"),(0,n.yg)("pre",null,(0,n.yg)("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.yg)("p",null,"Then, annotate the ",(0,n.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,n.yg)("pre",null,(0,n.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,n.yg)("pre",null,(0,n.yg)("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([[81],{69213:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>o,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>u});var r=a(58168),n=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},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.yg)(p,(0,r.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,n.yg)("p",{align:"center"},(0,n.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,n.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,n.yg)("h2",{id:"features"},"Features"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,n.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,n.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,n.yg)("h2",{id:"basic-example"},"Basic example"),(0,n.yg)("p",null,"First, declare a query in your controller:"),(0,n.yg)("pre",null,(0,n.yg)("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.yg)("p",null,"Then, annotate the ",(0,n.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,n.yg)("pre",null,(0,n.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,n.yg)("pre",null,(0,n.yg)("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.700a4ca5.js b/assets/js/58e6b30f.1331fed5.js similarity index 99% rename from assets/js/58e6b30f.700a4ca5.js rename to assets/js/58e6b30f.1331fed5.js index cd0c7c962..a9b72d89f 100644 --- a/assets/js/58e6b30f.700a4ca5.js +++ b/assets/js/58e6b30f.1331fed5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9798],{81346:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],c={toc:d},p="wrapper";function u(e){let{components:n,...t}=e;return(0,i.yg)(p,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,i.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,i.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,i.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,i.yg)("p",null,"GraphQLite allows you to use a ",(0,i.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,i.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,i.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("p",null,"In methods with a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotaiton, the first parameter is the ",(0,i.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,i.yg)("h2",{id:"sourcefield-annotation"},(0,i.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,i.yg)("p",null,"If you don't want to rewrite all ",(0,i.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,i.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,i.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"isName()"),")."),(0,i.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,i.yg)("p",null,"You may also check for logged users or users with a specific right using the ",(0,i.yg)("inlineCode",{parentName:"p"},"logged")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"right")," properties of the annotation:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Just like the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @SourceField(name="status", logged=true, right=@Right(name="CAN_ACCESS_STATUS"), failWith=null)\n */\n')),(0,i.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,i.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,i.yg)("pre",null,(0,i.yg)("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([[9798],{81346:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],c={toc:d},p="wrapper";function u(e){let{components:n,...t}=e;return(0,i.yg)(p,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,i.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,i.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,i.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,i.yg)("p",null,"GraphQLite allows you to use a ",(0,i.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,i.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,i.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("p",null,"In methods with a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotaiton, the first parameter is the ",(0,i.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,i.yg)("h2",{id:"sourcefield-annotation"},(0,i.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,i.yg)("p",null,"If you don't want to rewrite all ",(0,i.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,i.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,i.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"isName()"),")."),(0,i.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,i.yg)("p",null,"You may also check for logged users or users with a specific right using the ",(0,i.yg)("inlineCode",{parentName:"p"},"logged")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"right")," properties of the annotation:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Just like the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @SourceField(name="status", logged=true, right=@Right(name="CAN_ACCESS_STATUS"), failWith=null)\n */\n')),(0,i.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,i.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,i.yg)("pre",null,(0,i.yg)("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.993bc61e.js b/assets/js/5945e8b0.b053de15.js similarity index 99% rename from assets/js/5945e8b0.993bc61e.js rename to assets/js/5945e8b0.b053de15.js index e66aeba1a..fb3f8675e 100644 --- a/assets/js/5945e8b0.993bc61e.js +++ b/assets/js/5945e8b0.b053de15.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4773],{42056:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,i.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Now, go to the ",(0,i.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,i.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,i.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Now, go to the ",(0,i.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,i.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>o,toc:()=>d});var n=a(58168),r=(a(96540),a(15680));a(67443);const i={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},l=void 0,o={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/next/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.yg)(u,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, subscriptions, mapping of arrays / iterators,\nfile uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("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([[4485],{25890:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>o,toc:()=>d});var n=a(58168),r=(a(96540),a(15680));a(67443);const i={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},l=void 0,o={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/next/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.yg)(u,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, subscriptions, mapping of arrays / iterators,\nfile uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("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/5a9b411c.5b8587bb.js b/assets/js/5a9b411c.e5c6ed99.js similarity index 99% rename from assets/js/5a9b411c.5b8587bb.js rename to assets/js/5a9b411c.e5c6ed99.js index 2809bdc3b..2cb44c52f 100644 --- a/assets/js/5a9b411c.5b8587bb.js +++ b/assets/js/5a9b411c.e5c6ed99.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3693],{90052:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>l,default:()=>d,frontMatter:()=>o,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function d(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"config/graphqlite.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"config/graphqlite.php")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Sample Apollo client setup with CSRF support")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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([[3693],{90052:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>l,default:()=>d,frontMatter:()=>o,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function d(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"config/graphqlite.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"config/graphqlite.php")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Sample Apollo client setup with CSRF support")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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/5b80a12a.5dab1277.js b/assets/js/5b80a12a.472efb90.js similarity index 99% rename from assets/js/5b80a12a.5dab1277.js rename to assets/js/5b80a12a.472efb90.js index 4c8c4063d..b27167172 100644 --- a/assets/js/5b80a12a.5dab1277.js +++ b/assets/js/5b80a12a.472efb90.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4299],{49536:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-8.0.0/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-8.0.0/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/internals.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Type]")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"#[ExtendType]")," attribute and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4299],{49536:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-8.0.0/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-8.0.0/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/internals.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Type]")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"#[ExtendType]")," attribute and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5bc7272e.2bdba581.js b/assets/js/5bc7272e.6ff8df15.js similarity index 99% rename from assets/js/5bc7272e.2bdba581.js rename to assets/js/5bc7272e.6ff8df15.js index b8c794573..12dfad5df 100644 --- a/assets/js/5bc7272e.2bdba581.js +++ b/assets/js/5bc7272e.6ff8df15.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9454],{7061:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"version-7.0.0/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-7.0.0/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/7.0.0/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/migrating.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"docs",previous:{title:"Troubleshooting",permalink:"/docs/7.0.0/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/7.0.0/doctrine-annotations-attributes"}},s={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/7.0.0/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/7.0.0/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9454],{7061:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"version-7.0.0/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-7.0.0/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/7.0.0/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/migrating.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"docs",previous:{title:"Troubleshooting",permalink:"/docs/7.0.0/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/7.0.0/doctrine-annotations-attributes"}},s={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/7.0.0/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/7.0.0/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5d7590c2.bd4657d8.js b/assets/js/5d7590c2.d4fc2faa.js similarity index 98% rename from assets/js/5d7590c2.bd4657d8.js rename to assets/js/5d7590c2.d4fc2faa.js index ebdc7aee0..3d59e94fe 100644 --- a/assets/js/5d7590c2.bd4657d8.js +++ b/assets/js/5d7590c2.d4fc2faa.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9336],{43268:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>d,frontMatter:()=>r,metadata:()=>s,toc:()=>p});var n=a(58168),i=(a(96540),a(15680));a(67443);const r={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},o=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},l={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],u={toc:p},g="wrapper";function d(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,n.A)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,i.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,i.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,i.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,i.yg)("h2",{id:"installation"},"Installation"),(0,i.yg)("p",null,"You will need to install the ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,i.yg)("h2",{id:"usage"},"Usage"),(0,i.yg)("p",null,"In your query, simply return a class that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Notice that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,i.yg)("li",{parentName:"ul"},"you MUST add a ",(0,i.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,i.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,i.yg)("p",null,'The "count" field returns the ',(0,i.yg)("strong",{parentName:"p"},"total count")," of items."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9336],{43268:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>d,frontMatter:()=>r,metadata:()=>s,toc:()=>p});var n=a(58168),i=(a(96540),a(15680));a(67443);const r={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},o=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},l={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],u={toc:p},g="wrapper";function d(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,n.A)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,i.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,i.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,i.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,i.yg)("h2",{id:"installation"},"Installation"),(0,i.yg)("p",null,"You will need to install the ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,i.yg)("h2",{id:"usage"},"Usage"),(0,i.yg)("p",null,"In your query, simply return a class that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Notice that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,i.yg)("li",{parentName:"ul"},"you MUST add a ",(0,i.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,i.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,i.yg)("p",null,'The "count" field returns the ',(0,i.yg)("strong",{parentName:"p"},"total count")," of items."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5d95c2e4.6d20fea0.js b/assets/js/5d95c2e4.13c08a29.js similarity index 97% rename from assets/js/5d95c2e4.6d20fea0.js rename to assets/js/5d95c2e4.13c08a29.js index 7b790d1df..3167e70b5 100644 --- a/assets/js/5d95c2e4.6d20fea0.js +++ b/assets/js/5d95c2e4.13c08a29.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7146],{11302:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>o,toc:()=>d});var n=a(58168),r=(a(96540),a(15680));a(67443);const i={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},l=void 0,o={unversionedId:"index",id:"version-8.0.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-8.0.0/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/README.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(u,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, subscriptions, mapping of arrays / iterators,\nfile uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("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([[7146],{11302:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>o,toc:()=>d});var n=a(58168),r=(a(96540),a(15680));a(67443);const i={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},l=void 0,o={unversionedId:"index",id:"version-8.0.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-8.0.0/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/README.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(u,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, subscriptions, mapping of arrays / iterators,\nfile uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("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/5dde70bf.4154cee0.js b/assets/js/5dde70bf.477b054f.js similarity index 99% rename from assets/js/5dde70bf.4154cee0.js rename to assets/js/5dde70bf.477b054f.js index 592a2a88b..d98d5bde8 100644 --- a/assets/js/5dde70bf.4154cee0.js +++ b/assets/js/5dde70bf.477b054f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[288],{73287:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},l=void 0,o={unversionedId:"symfony-bundle",id:"version-7.0.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-7.0.0/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/7.0.0/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/symfony-bundle.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"docs",previous:{title:"Getting Started",permalink:"/docs/7.0.0/getting-started"},next:{title:"Laravel package",permalink:"/docs/7.0.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 g(e){let{components:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,i.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Now, go to the ",(0,i.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,i.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);const r={id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},l=void 0,o={unversionedId:"symfony-bundle",id:"version-7.0.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-7.0.0/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/7.0.0/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/symfony-bundle.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"docs",previous:{title:"Getting Started",permalink:"/docs/7.0.0/getting-started"},next:{title:"Laravel package",permalink:"/docs/7.0.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 g(e){let{components:n,...t}=e;return(0,i.yg)(d,(0,a.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,i.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,i.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,i.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,i.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,i.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Now, go to the ",(0,i.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,i.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,i.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,i.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,i.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,i.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="app/AppKernel.php"',title:'"app/AppKernel.php"'},"{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function u(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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([[2347],{83162:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function u(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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.a0ec87fc.js b/assets/js/5e352ef4.0bebc6a8.js similarity index 99% rename from assets/js/5e352ef4.a0ec87fc.js rename to assets/js/5e352ef4.0bebc6a8.js index 9473adb27..58c65f0e5 100644 --- a/assets/js/5e352ef4.a0ec87fc.js +++ b/assets/js/5e352ef4.0bebc6a8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[104],{19365:(e,a,t)=>{t.d(a,{A:()=>o});var n=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:a,hidden:t,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>N});var n=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),s=t(57485),u=t(31682),d=t(89466);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function c(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??p(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function m(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,l.W6)(),i=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const a=new URLSearchParams(n.location.search);a.set(i,e),n.replace({...n.location,search:a.toString()})}),[i,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!m({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:i}))),[s,u]=y({queryString:t,groupId:n}),[p,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,i]=(0,d.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:n}),g=(()=>{const e=s??p;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),h(e)}),[u,h,i]),tabValues:i}}var g=t(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:a,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),c=e=>{const a=e.currentTarget,t=d.indexOf(a),n=u[t].value;n!==l&&(p(a),s(n))},m=e=>{let a=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const t=d.indexOf(e.currentTarget)+1;a=d[t]??d[0];break}case"ArrowLeft":{const t=d.indexOf(e.currentTarget)-1;a=d[t]??d[d.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.A)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=h(e);return r.createElement("div",{className:(0,i.A)("tabs-container",v.tabList)},r.createElement(f,(0,n.A)({},e,a)),r.createElement(b,(0,n.A)({},e,a)))}function N(e){const a=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},49786:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>s,default:()=>y,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 y(e){let{components:a,...t}=e;return(0,r.yg)(m,(0,n.A)({},c,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box"),(0,r.yg)("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.yg)("em",{parentName:"li"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:",(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"UserController.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"UserController.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"User.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"User.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,r.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.yg)("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.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.yg)("p",null,"You can also pass an array to the ",(0,r.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.yg)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[104],{19365:(e,a,t)=>{t.d(a,{A:()=>o});var n=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:a,hidden:t,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>N});var n=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),s=t(57485),u=t(31682),d=t(89466);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function c(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??p(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function m(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,l.W6)(),i=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const a=new URLSearchParams(n.location.search);a.set(i,e),n.replace({...n.location,search:a.toString()})}),[i,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!m({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:i}))),[s,u]=y({queryString:t,groupId:n}),[p,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,i]=(0,d.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:n}),g=(()=>{const e=s??p;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),h(e)}),[u,h,i]),tabValues:i}}var g=t(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:a,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),c=e=>{const a=e.currentTarget,t=d.indexOf(a),n=u[t].value;n!==l&&(p(a),s(n))},m=e=>{let a=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const t=d.indexOf(e.currentTarget)+1;a=d[t]??d[0];break}case"ArrowLeft":{const t=d.indexOf(e.currentTarget)-1;a=d[t]??d[d.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.A)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=h(e);return r.createElement("div",{className:(0,i.A)("tabs-container",v.tabList)},r.createElement(f,(0,n.A)({},e,a)),r.createElement(b,(0,n.A)({},e,a)))}function N(e){const a=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},49786:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>s,default:()=>y,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 y(e){let{components:a,...t}=e;return(0,r.yg)(m,(0,n.A)({},c,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box"),(0,r.yg)("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.yg)("em",{parentName:"li"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:",(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"UserController.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"UserController.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"User.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"User.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,r.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.yg)("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.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.yg)("p",null,"You can also pass an array to the ",(0,r.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.yg)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5e457383.7f5ab153.js b/assets/js/5e457383.d7e58f2f.js similarity index 97% rename from assets/js/5e457383.7f5ab153.js rename to assets/js/5e457383.d7e58f2f.js index 90108605f..4d3587d45 100644 --- a/assets/js/5e457383.7f5ab153.js +++ b/assets/js/5e457383.d7e58f2f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3457],{42799:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-7.0.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-7.0.0/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/7.0.0/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/semver.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Annotations reference",permalink:"/docs/7.0.0/annotations-reference"},next:{title:"Changelog",permalink:"/docs/7.0.0/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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([[3457],{42799:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);const i={id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},o=void 0,s={unversionedId:"semver",id:"version-7.0.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-7.0.0/semver.md",sourceDirName:".",slug:"/semver",permalink:"/docs/7.0.0/semver",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/semver.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Annotations reference",permalink:"/docs/7.0.0/annotations-reference"},next:{title:"Changelog",permalink:"/docs/7.0.0/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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/5ec7a7fe.9f1d1734.js b/assets/js/5ec7a7fe.6f344f93.js similarity index 99% rename from assets/js/5ec7a7fe.9f1d1734.js rename to assets/js/5ec7a7fe.6f344f93.js index d04f2eacf..71d77f0d1 100644 --- a/assets/js/5ec7a7fe.9f1d1734.js +++ b/assets/js/5ec7a7fe.6f344f93.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2676],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var a=t(96540),r=t(20053);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.A)(l.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),r=t(96540),l=t(20053),i=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);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.X)(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 g(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,o.W6)(),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.aZ)(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 y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=d(e),[i,o]=(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(!g({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,p.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),m=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const n=e.currentTarget,t=p.indexOf(n),a=u[t].value;a!==o&&(c(n),s(a))},g=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,l.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(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 T(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(n)},e))}},40631:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),i=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function h(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Using ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Let's break this sample:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.yg)("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.yg)("p",null,'Using the "',(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2676],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var a=t(96540),r=t(20053);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.A)(l.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),r=t(96540),l=t(20053),i=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);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.X)(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 g(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,o.W6)(),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.aZ)(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 y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=d(e),[i,o]=(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(!g({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,p.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),m=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const n=e.currentTarget,t=p.indexOf(n),a=u[t].value;a!==o&&(c(n),s(a))},g=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,l.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(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 T(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(n)},e))}},40631:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),i=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function h(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Using ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Let's break this sample:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.yg)("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.yg)("p",null,'Using the "',(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5ececfab.58345f33.js b/assets/js/5ececfab.3e198c19.js similarity index 99% rename from assets/js/5ececfab.58345f33.js rename to assets/js/5ececfab.3e198c19.js index 061675efc..ee575ccfb 100644 --- a/assets/js/5ececfab.58345f33.js +++ b/assets/js/5ececfab.3e198c19.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2275],{19365:(e,n,a)=>{a.d(n,{A:()=>r});var t=a(96540),p=a(20053);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:a,className:r}=e;return t.createElement("div",{role:"tabpanel",className:(0,p.A)(l.tabItem,r),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>N});var t=a(58168),p=a(96540),l=a(20053),r=a(23104),s=a(56347),i=a(57485),u=a(31682),o=a(89466);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:a,attributes:t,default:p}}=e;return{value:n,label:a,attributes:t,default:p}}))}function m(e){const{values:n,children:a}=e;return(0,p.useMemo)((()=>{const e=n??c(a);return function(e){const n=(0,u.X)(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,a])}function y(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,i.aZ)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function g(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!y({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[i,u]=d({queryString:a,groupId:t}),[c,g]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,p.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=i??c;return y({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{h&&s(h)}),[h]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!y({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 h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=u[a].value;t!==s&&(c(n),i(t))},y=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},u.map((e=>{let{value:n,label:a,attributes:r}=e;return p.createElement("li",(0,t.A)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:y,onClick:m},r,{className:(0,l.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function T(e){const n=g(e);return p.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},p.createElement(b,(0,t.A)({},e,n)),p.createElement(v,(0,t.A)({},e,n)))}function N(e){const n=(0,h.A)();return p.createElement(T,(0,t.A)({key:String(n)},e))}},61314:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>i,default:()=>d,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var t=a(58168),p=(a(96540),a(15680)),l=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.3/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.3/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"You can create a GraphQL union type ",(0,p.yg)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.yg)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.yg)("p",null,"You will first need to install ",(0,p.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("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.yg)("em",null,"type mappers")," in the ",(0,p.yg)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.yg)("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.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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([[2275],{19365:(e,n,a)=>{a.d(n,{A:()=>r});var t=a(96540),p=a(20053);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:a,className:r}=e;return t.createElement("div",{role:"tabpanel",className:(0,p.A)(l.tabItem,r),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>N});var t=a(58168),p=a(96540),l=a(20053),r=a(23104),s=a(56347),i=a(57485),u=a(31682),o=a(89466);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:a,attributes:t,default:p}}=e;return{value:n,label:a,attributes:t,default:p}}))}function m(e){const{values:n,children:a}=e;return(0,p.useMemo)((()=>{const e=n??c(a);return function(e){const n=(0,u.X)(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,a])}function y(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,i.aZ)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function g(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!y({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[i,u]=d({queryString:a,groupId:t}),[c,g]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,p.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=i??c;return y({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{h&&s(h)}),[h]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!y({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 h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=u[a].value;t!==s&&(c(n),i(t))},y=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},u.map((e=>{let{value:n,label:a,attributes:r}=e;return p.createElement("li",(0,t.A)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:y,onClick:m},r,{className:(0,l.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function T(e){const n=g(e);return p.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},p.createElement(b,(0,t.A)({},e,n)),p.createElement(v,(0,t.A)({},e,n)))}function N(e){const n=(0,h.A)();return p.createElement(T,(0,t.A)({key:String(n)},e))}},61314:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>i,default:()=>d,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var t=a(58168),p=(a(96540),a(15680)),l=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.3/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.3/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"You can create a GraphQL union type ",(0,p.yg)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.yg)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.yg)("p",null,"You will first need to install ",(0,p.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("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.yg)("em",null,"type mappers")," in the ",(0,p.yg)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.yg)("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.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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/5fa4a5b6.abbb7da4.js b/assets/js/5fa4a5b6.f2b014e5.js similarity index 99% rename from assets/js/5fa4a5b6.abbb7da4.js rename to assets/js/5fa4a5b6.f2b014e5.js index b53f9593e..0794bf780 100644 --- a/assets/js/5fa4a5b6.abbb7da4.js +++ b/assets/js/5fa4a5b6.f2b014e5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3355],{19365:(e,n,t)=>{t.d(n,{A:()=>u});var a=t(96540),l=t(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:n,hidden:t,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),l=t(96540),r=t(20053),u=t(23104),o=t(56347),i=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.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:l}}=e;return{value:n,label:t,attributes:a,default:l}}))}function m(e){const{values:n,children:t}=e;return(0,l.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,o.W6)(),r=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.aZ)(r),(0,l.useCallback)((e=>{if(!r)return;const n=new URLSearchParams(a.location.search);n.set(r,e),a.replace({...a.location,search:n.toString()})}),[r,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,r=m(e),[u,o]=(0,l.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:r}))),[i,s]=g({queryString:t,groupId:a}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,r]=(0,c.Dv)(t);return[a,(0,l.useCallback)((e=>{t&&r.set(e)}),[t,r])]}({groupId:a}),h=(()=>{const e=i??p;return d({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);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),y(e)}),[s,y,r]),tabValues:r}}var h=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),m=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==o&&(p(n),i(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(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 l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:u}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:m},u,{className:(0,r.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const r=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,l.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function q(e){const n=y(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,n)),l.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(n)},e))}},42462:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=t(58168),l=(t(96540),t(15680)),r=(t(67443),t(11470)),u=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],m={toc:p},d="wrapper";function g(e){let{components:n,...t}=e;return(0,l.yg)(d,(0,a.A)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.yg)("p",null,"By settings ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.yg)("p",null,"The mutation below will log-in a user:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.yg)("p",null,"In Symfony, user objects implement ",(0,l.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.yg)("p",null,"If you want to get more fields, just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"You can now query this field using an ",(0,l.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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")))))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3355],{19365:(e,n,t)=>{t.d(n,{A:()=>u});var a=t(96540),l=t(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:n,hidden:t,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),l=t(96540),r=t(20053),u=t(23104),o=t(56347),i=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.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:l}}=e;return{value:n,label:t,attributes:a,default:l}}))}function m(e){const{values:n,children:t}=e;return(0,l.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,o.W6)(),r=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.aZ)(r),(0,l.useCallback)((e=>{if(!r)return;const n=new URLSearchParams(a.location.search);n.set(r,e),a.replace({...a.location,search:n.toString()})}),[r,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,r=m(e),[u,o]=(0,l.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:r}))),[i,s]=g({queryString:t,groupId:a}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,r]=(0,c.Dv)(t);return[a,(0,l.useCallback)((e=>{t&&r.set(e)}),[t,r])]}({groupId:a}),h=(()=>{const e=i??p;return d({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);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),y(e)}),[s,y,r]),tabValues:r}}var h=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),m=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==o&&(p(n),i(a))},d=e=>{let n=null;switch(e.key){case"Enter":m(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 l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:u}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>c.push(e),onKeyDown:d,onClick:m},u,{className:(0,r.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const r=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,l.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function q(e){const n=y(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,n)),l.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(n)},e))}},42462:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=t(58168),l=(t(96540),t(15680)),r=(t(67443),t(11470)),u=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],m={toc:p},d="wrapper";function g(e){let{components:n,...t}=e;return(0,l.yg)(d,(0,a.A)({},m,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.yg)("p",null,"By settings ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.yg)("p",null,"The mutation below will log-in a user:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.yg)("p",null,"In Symfony, user objects implement ",(0,l.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.yg)("p",null,"If you want to get more fields, just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"You can now query this field using an ",(0,l.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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")))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5fb37434.63d9cb43.js b/assets/js/5fb37434.af064a87.js similarity index 98% rename from assets/js/5fb37434.63d9cb43.js rename to assets/js/5fb37434.af064a87.js index afe2ea9b4..1b6113f9d 100644 --- a/assets/js/5fb37434.63d9cb43.js +++ b/assets/js/5fb37434.af064a87.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8871],{85144:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>u});var a=t(58168),r=(t(96540),t(15680));t(67443);const o={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},l=void 0,i={unversionedId:"query-plan",id:"version-8.0.0/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/query-plan.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"docs",previous:{title:"Operation complexity",permalink:"/docs/operation-complexity"},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:n,...t}=e;return(0,r.yg)(d,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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([[8871],{85144:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>u});var a=t(58168),r=(t(96540),t(15680));t(67443);const o={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},l=void 0,i={unversionedId:"query-plan",id:"version-8.0.0/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/query-plan.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"docs",previous:{title:"Operation complexity",permalink:"/docs/operation-complexity"},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:n,...t}=e;return(0,r.yg)(d,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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/5ffc8074.2da3d499.js b/assets/js/5ffc8074.a35bb01d.js similarity index 99% rename from assets/js/5ffc8074.2da3d499.js rename to assets/js/5ffc8074.a35bb01d.js index bab2e0425..5168a91be 100644 --- a/assets/js/5ffc8074.2da3d499.js +++ b/assets/js/5ffc8074.a35bb01d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4122],{78377:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(58168),l=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},g={},p=[{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}],y={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,l.yg)(d,(0,a.A)({},y,n,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("a",{parentName:"td",href:"/docs/3.0/external_type_declaration"},"the class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")))),(0,l.yg)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/3.0/extend_type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")))),(0,l.yg)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"logged"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether the user must be logged or not to see the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"right"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"Right annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"The right the user must have to see the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"failWith"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("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.yg)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4122],{78377:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(58168),l=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},g={},p=[{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}],y={toc:p},d="wrapper";function m(e){let{components:t,...n}=e;return(0,l.yg)(d,(0,a.A)({},y,n,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("a",{parentName:"td",href:"/docs/3.0/external_type_declaration"},"the class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")))),(0,l.yg)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/3.0/extend_type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")))),(0,l.yg)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/3.0/type_mapping"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"logged"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether the user must be logged or not to see the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"right"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"Right annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"The right the user must have to see the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"failWith"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("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.yg)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the input type. If skipped, the name of class returned by the factory is used instead.")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/606959d6.c75b1bce.js b/assets/js/606959d6.cd0e5d4c.js similarity index 99% rename from assets/js/606959d6.c75b1bce.js rename to assets/js/606959d6.cd0e5d4c.js index cd9761e09..7737be9f1 100644 --- a/assets/js/606959d6.c75b1bce.js +++ b/assets/js/606959d6.cd0e5d4c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[862],{19365:(e,a,n)=>{n.d(a,{A:()=>i});var t=n(96540),r=n(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:a,hidden:n,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:n},a)}},11470:(e,a,n)=>{n.d(a,{A:()=>T});var t=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),p=n(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:n,attributes:t,default:r}}=e;return{value:a,label:n,attributes:t,default:r}}))}function d(e){const{values:a,children:n}=e;return(0,r.useMemo)((()=>{const e=a??c(n);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,n])}function g(e){let{value:a,tabValues:n}=e;return n.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:n}=e;const t=(0,o.W6)(),l=function(e){let{queryString:a=!1,groupId:n}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:n});return[(0,s.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(t.location.search);a.set(l,e),t.replace({...t.location,search:a.toString()})}),[l,t])]}function m(e){const{defaultValue:a,queryString:n=!1,groupId:t}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const t=n.find((e=>e.default))??n[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:a,tabValues:l}))),[s,u]=h({queryString:n,groupId:t}),[c,m]=function(e){let{groupId:a}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(a),[t,l]=(0,p.Dv)(n);return[t,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:t}),y=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,l]),tabValues:l}}var y=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const a=e.currentTarget,n=p.indexOf(a),t=u[n].value;t!==o&&(c(a),s(t))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;a=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;a=p[n]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":n},a)},u.map((e=>{let{value:a,label:n,attributes:i}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===a})}),n??a)})))}function b(e){let{lazy:a,children:n,selectedValue:t}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(a){const e=l.find((e=>e.props.value===t));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==t}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(v,(0,t.A)({},e,a)),r.createElement(b,(0,t.A)({},e,a)))}function T(e){const a=(0,y.A)();return r.createElement(w,(0,t.A)({key:String(a)},e))}},4531:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var t=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},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},g="wrapper";function h(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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'))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[862],{19365:(e,a,n)=>{n.d(a,{A:()=>i});var t=n(96540),r=n(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:a,hidden:n,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:n},a)}},11470:(e,a,n)=>{n.d(a,{A:()=>T});var t=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),p=n(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:n,attributes:t,default:r}}=e;return{value:a,label:n,attributes:t,default:r}}))}function d(e){const{values:a,children:n}=e;return(0,r.useMemo)((()=>{const e=a??c(n);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,n])}function g(e){let{value:a,tabValues:n}=e;return n.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:n}=e;const t=(0,o.W6)(),l=function(e){let{queryString:a=!1,groupId:n}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:n});return[(0,s.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(t.location.search);a.set(l,e),t.replace({...t.location,search:a.toString()})}),[l,t])]}function m(e){const{defaultValue:a,queryString:n=!1,groupId:t}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const t=n.find((e=>e.default))??n[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:a,tabValues:l}))),[s,u]=h({queryString:n,groupId:t}),[c,m]=function(e){let{groupId:a}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(a),[t,l]=(0,p.Dv)(n);return[t,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:t}),y=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,l]),tabValues:l}}var y=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const a=e.currentTarget,n=p.indexOf(a),t=u[n].value;t!==o&&(c(a),s(t))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;a=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;a=p[n]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":n},a)},u.map((e=>{let{value:a,label:n,attributes:i}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===a})}),n??a)})))}function b(e){let{lazy:a,children:n,selectedValue:t}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(a){const e=l.find((e=>e.props.value===t));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==t}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(v,(0,t.A)({},e,a)),r.createElement(b,(0,t.A)({},e,a)))}function T(e){const a=(0,y.A)();return r.createElement(w,(0,t.A)({key:String(a)},e))}},4531:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var t=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},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},g="wrapper";function h(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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'))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/607daa94.a7a587eb.js b/assets/js/607daa94.4dc9730b.js similarity index 99% rename from assets/js/607daa94.a7a587eb.js rename to assets/js/607daa94.4dc9730b.js index 58df0359a..e469fce90 100644 --- a/assets/js/607daa94.a7a587eb.js +++ b/assets/js/607daa94.4dc9730b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7041],{70837:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>o,default:()=>c,frontMatter:()=>r,metadata:()=>y,toc:()=>l});var n=a(58168),p=(a(96540),a(15680));a(67443);const r={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},o=void 0,y={unversionedId:"custom-types",id:"version-8.0.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-8.0.0/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-8.0.0/custom-types.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/pagination"},next:{title:"Custom attributes",permalink:"/docs/field-middlewares"}},i={},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},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],s={toc:l},u="wrapper";function c(e){let{components:t,...a}=e;return(0,p.yg)(u,(0,n.A)({},s,a,{components:t,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.yg)("p",null,"GraphQL comes with an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n')),(0,p.yg)("h2",{id:"usage"},"Usage"),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.yg)("p",null,"You can use the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Query]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Mutation]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Subscription]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Field]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[SourceField]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[MagicField]"))),(0,p.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.yg)("p",null,"In order to create a custom output type, you need to:"),(0,p.yg)("ol",null,(0,p.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,p.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.yg)("p",null,"You'll find more details on the ",(0,p.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,p.yg)("hr",null),(0,p.yg)("p",null,"In order to find existing types, the schema is using ",(0,p.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,p.yg)("p",null,"Any class extending ",(0,p.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.yg)("p",null,"The easiest way is to use a ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,p.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,p.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,p.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},"create a ",(0,p.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,p.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,p.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,p.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,p.yg)("p",null,"RootTypeMapper are organized ",(0,p.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,p.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("p",null,"Now, in order to create an instance of your ",(0,p.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,p.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,p.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,p.yg)("p",null,"You can register your own root mapper factories using the ",(0,p.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,p.yg)("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([[7041],{70837:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>o,default:()=>c,frontMatter:()=>r,metadata:()=>y,toc:()=>l});var n=a(58168),p=(a(96540),a(15680));a(67443);const r={id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},o=void 0,y={unversionedId:"custom-types",id:"version-8.0.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-8.0.0/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-8.0.0/custom-types.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/pagination"},next:{title:"Custom attributes",permalink:"/docs/field-middlewares"}},i={},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},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],s={toc:l},u="wrapper";function c(e){let{components:t,...a}=e;return(0,p.yg)(u,(0,n.A)({},s,a,{components:t,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.yg)("p",null,"GraphQL comes with an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n')),(0,p.yg)("h2",{id:"usage"},"Usage"),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.yg)("p",null,"You can use the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Query]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Mutation]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Subscription]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[Field]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[SourceField]")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"#[MagicField]"))),(0,p.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.yg)("p",null,"In order to create a custom output type, you need to:"),(0,p.yg)("ol",null,(0,p.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,p.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.yg)("p",null,"You'll find more details on the ",(0,p.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,p.yg)("hr",null),(0,p.yg)("p",null,"In order to find existing types, the schema is using ",(0,p.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,p.yg)("p",null,"Any class extending ",(0,p.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.yg)("p",null,"The easiest way is to use a ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,p.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,p.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,p.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},"create a ",(0,p.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,p.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,p.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,p.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,p.yg)("p",null,"RootTypeMapper are organized ",(0,p.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,p.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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,p.yg)("p",null,"Now, in order to create an instance of your ",(0,p.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,p.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,p.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,p.yg)("p",null,"You can register your own root mapper factories using the ",(0,p.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,p.yg)("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/60d99771.3813694a.js b/assets/js/60d99771.5b04a0fd.js similarity index 98% rename from assets/js/60d99771.3813694a.js rename to assets/js/60d99771.5b04a0fd.js index 5d8a273f4..2cbe668a9 100644 --- a/assets/js/60d99771.3813694a.js +++ b/assets/js/60d99771.5b04a0fd.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5356],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>q});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),u=n(56347),s=n(57485),i=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&u(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}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":u===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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function q(e){const t=(0,y.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},10821:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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([[5356],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>q});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),u=n(56347),s=n(57485),i=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&u(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}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":u===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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function q(e){const t=(0,y.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},10821:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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.71f37a5e.js b/assets/js/610e7425.8f1eebec.js similarity index 99% rename from assets/js/610e7425.71f37a5e.js rename to assets/js/610e7425.8f1eebec.js index edf4fe891..5a0529f1f 100644 --- a/assets/js/610e7425.71f37a5e.js +++ b/assets/js/610e7425.8f1eebec.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4279],{28754:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>l,default:()=>m,frontMatter:()=>r,metadata:()=>s,toc:()=>c});var t=a(58168),i=(a(96540),a(15680));a(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"docs",previous:{title:"Input types",permalink:"/docs/6.1/input-types"},next:{title:"Error handling",permalink:"/docs/6.1/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},g="wrapper";function m(e){let{components:n,...a}=e;return(0,i.yg)(g,(0,t.A)({},o,a,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,i.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.yg)("p",null,"Written in ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.yg)("p",null,"The GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,i.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n")),(0,i.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,i.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.yg)("p",null,"This will translate in GraphQL schema as:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,i.yg)("p",null,"Please note that you do not need to put the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,i.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,i.yg)("p",null,"You don't have to explicitly put a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,i.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,i.yg)("pre",null,(0,i.yg)("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([[4279],{28754:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>l,default:()=>m,frontMatter:()=>r,metadata:()=>s,toc:()=>c});var t=a(58168),i=(a(96540),a(15680));a(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"docs",previous:{title:"Input types",permalink:"/docs/6.1/input-types"},next:{title:"Error handling",permalink:"/docs/6.1/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},g="wrapper";function m(e){let{components:n,...a}=e;return(0,i.yg)(g,(0,t.A)({},o,a,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,i.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.yg)("p",null,"Written in ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.yg)("p",null,"The GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,i.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n")),(0,i.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,i.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.yg)("p",null,"This will translate in GraphQL schema as:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,i.yg)("p",null,"Please note that you do not need to put the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,i.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,i.yg)("p",null,"You don't have to explicitly put a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,i.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,i.yg)("pre",null,(0,i.yg)("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.6e04135c.js b/assets/js/612b773e.a8952612.js similarity index 96% rename from assets/js/612b773e.6e04135c.js rename to assets/js/612b773e.a8952612.js index bbe5a292e..28d5eda70 100644 --- a/assets/js/612b773e.6e04135c.js +++ b/assets/js/612b773e.a8952612.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5646],{51054:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>p,frontMatter:()=>o,metadata:()=>r,toc:()=>c});var a=n(58168),i=(n(96540),n(15680));n(67443);const o={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,r={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/next/queries"},next:{title:"Subscriptions",permalink:"/docs/next/subscriptions"}},u={},c=[],d={toc:c},l="wrapper";function p(t){let{components:e,...n}=t;return(0,i.yg)(l,(0,a.A)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, mutations are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/queries"},"like queries"),"."),(0,i.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," attribute."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("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")))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5646],{51054:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>p,frontMatter:()=>o,metadata:()=>r,toc:()=>c});var a=n(58168),i=(n(96540),n(15680));n(67443);const o={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,r={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/next/queries"},next:{title:"Subscriptions",permalink:"/docs/next/subscriptions"}},u={},c=[],d={toc:c},l="wrapper";function p(t){let{components:e,...n}=t;return(0,i.yg)(l,(0,a.A)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, mutations are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/queries"},"like queries"),"."),(0,i.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," attribute."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("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")))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/61595218.830cce27.js b/assets/js/61595218.dcfd472d.js similarity index 99% rename from assets/js/61595218.830cce27.js rename to assets/js/61595218.dcfd472d.js index 7d15575d6..5db6e76c3 100644 --- a/assets/js/61595218.830cce27.js +++ b/assets/js/61595218.dcfd472d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9775],{78764:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>o,toc:()=>g});var n=a(58168),l=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],y={toc:g},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.yg)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.yg)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("a",{parentName:"td",href:"/docs/4.2/external-type-declaration"},"the class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("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.yg)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/4.2/extend-type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"input-annotation"},"@Input annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true")," if name is not specified. Whether the annotated PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"update"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.yg)("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.yg)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.yg)("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.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"for"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string, array"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.2/input-types"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.yg)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"value"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("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.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9775],{78764:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>o,toc:()=>g});var n=a(58168),l=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],y={toc:g},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.yg)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.yg)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("a",{parentName:"td",href:"/docs/4.2/external-type-declaration"},"the class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("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.yg)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/4.2/extend-type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"input-annotation"},"@Input annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true")," if name is not specified. Whether the annotated PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"update"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.yg)("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.yg)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.yg)("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.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"for"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string, array"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.2/input-types"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.yg)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.2/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"value"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("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.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.2/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/617523b3.d0beb915.js b/assets/js/617523b3.757b91f1.js similarity index 99% rename from assets/js/617523b3.d0beb915.js rename to assets/js/617523b3.757b91f1.js index 38e65dcc1..38a9aafa0 100644 --- a/assets/js/617523b3.d0beb915.js +++ b/assets/js/617523b3.757b91f1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6924],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),l=a(20053);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.A)(u.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>P});var n=a(58168),l=a(96540),u=a(20053),r=a(23104),i=a(56347),o=a(57485),p=a(31682),s=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(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(!y({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]=m({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,s.Dv)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),g=(()=>{const e=o??d;return y({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),h(e)}),[p,h,u]),tabValues:u}}var g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.a_)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(d(t),o(n))},y=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.A)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.A)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:c},r,{className:(0,u.A)("tabs__item",f.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 T(e){const t=h(e);return l.createElement("div",{className:(0,u.A)("tabs-container",f.tabList)},l.createElement(b,(0,n.A)({},e,t)),l.createElement(v,(0,n.A)({},e,t)))}function P(e){const t=(0,g.A)();return l.createElement(T,(0,n.A)({key:String(t)},e))}},64643:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>m,frontMatter:()=>i,metadata:()=>p,toc:()=>d});var n=a(58168),l=(a(96540),a(15680)),u=(a(67443),a(11470)),r=a(19365);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"},o=void 0,p={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(y,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/external_type_declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("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.yg)("p",null,"So instead of writing:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.yg)("p",null,"you will write:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6924],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),l=a(20053);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.A)(u.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>P});var n=a(58168),l=a(96540),u=a(20053),r=a(23104),i=a(56347),o=a(57485),p=a(31682),s=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(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(!y({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]=m({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,s.Dv)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),g=(()=>{const e=o??d;return y({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),h(e)}),[p,h,u]),tabValues:u}}var g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.a_)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(d(t),o(n))},y=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.A)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.A)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:c},r,{className:(0,u.A)("tabs__item",f.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 T(e){const t=h(e);return l.createElement("div",{className:(0,u.A)("tabs-container",f.tabList)},l.createElement(b,(0,n.A)({},e,t)),l.createElement(v,(0,n.A)({},e,t)))}function P(e){const t=(0,g.A)();return l.createElement(T,(0,n.A)({key:String(t)},e))}},64643:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>m,frontMatter:()=>i,metadata:()=>p,toc:()=>d});var n=a(58168),l=(a(96540),a(15680)),u=(a(67443),a(11470)),r=a(19365);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"},o=void 0,p={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(y,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/external_type_declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("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.yg)("p",null,"So instead of writing:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.yg)("p",null,"you will write:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/61c7d915.69c85a33.js b/assets/js/61c7d915.fe654e35.js similarity index 98% rename from assets/js/61c7d915.69c85a33.js rename to assets/js/61c7d915.fe654e35.js index 1ce56cacb..64b764013 100644 --- a/assets/js/61c7d915.69c85a33.js +++ b/assets/js/61c7d915.fe654e35.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6621],{70267:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>u});var a=t(58168),r=(t(96540),t(15680));t(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"docs",previous:{title:"Connecting security to your framework",permalink:"/docs/6.1/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/6.1/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:n,...t}=e;return(0,r.yg)(d,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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([[6621],{70267:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>o,metadata:()=>i,toc:()=>u});var a=t(58168),r=(t(96540),t(15680));t(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"docs",previous:{title:"Connecting security to your framework",permalink:"/docs/6.1/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/6.1/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:n,...t}=e;return(0,r.yg)(d,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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.2efbceef.js b/assets/js/623b6c78.49a33252.js similarity index 99% rename from assets/js/623b6c78.2efbceef.js rename to assets/js/623b6c78.49a33252.js index d06cdc655..e1d95eefa 100644 --- a/assets/js/623b6c78.2efbceef.js +++ b/assets/js/623b6c78.49a33252.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7800],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(s.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),s=n(20053),o=n(23104),l=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("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 T(e){const t=f(e);return r.createElement("div",{className:(0,s.A)("tabs-container",y.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,b.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},27534:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),s=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.1/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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([[7800],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(s.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),s=n(20053),o=n(23104),l=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("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 T(e){const t=f(e);return r.createElement("div",{className:(0,s.A)("tabs-container",y.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,b.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},27534:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),s=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.1/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.1c63ec79.js b/assets/js/64536e1a.c293a5d2.js similarity index 99% rename from assets/js/64536e1a.1c63ec79.js rename to assets/js/64536e1a.c293a5d2.js index 8e72d6630..c18614689 100644 --- a/assets/js/64536e1a.1c63ec79.js +++ b/assets/js/64536e1a.c293a5d2.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2960],{10976:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>l,default:()=>h,frontMatter:()=>o,metadata:()=>r,toc:()=>s});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:t,...n}=e;return(0,i.yg)(y,(0,a.A)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("h2",{id:"query-depth"},"Query depth"),(0,i.yg)("p",null,"The simplest way to limit complexity is to limit the max query depth. ",(0,i.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php"),",\nwhich GraphQLite relies on, ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"addValidationRule")," when building your PSR15 middleware:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$builder->addValidationRule(new \\GraphQL\\Validator\\Rules\\QueryDepth(7));\n")),(0,i.yg)("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.yg)("h2",{id:"static-request-analysis"},"Static request analysis"),(0,i.yg)("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.yg)("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.yg)("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.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the above example executing the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field on the ",(0,i.yg)("inlineCode",{parentName:"p"},"Query")," type might go to the\ndatabase and fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"Book"),". This means that the cost of the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field is\nprobably higher than the cost of the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"title"),", the default\ncost of ",(0,i.yg)("inlineCode",{parentName:"p"},"1")," os OK. But for ",(0,i.yg)("inlineCode",{parentName:"p"},"books"),", we might want to go with a higher cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"10"),"\nsince we are getting a list of books from our database."),(0,i.yg)("p",null,"Moreover, we have the field ",(0,i.yg)("inlineCode",{parentName:"p"},"author")," on the book, which might go to the database\nas well to fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"Author")," object. Since we are only fetching a single item here,\nwe might want to apply a cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"5")," to this field."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"If we run the following query against our data graph, we will come up with the cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"11"),"."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.yg)("p",null,"When drilling in further, a cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"17")," occurs."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"10")," even though we might get one or one\nhundred books back?"),(0,i.yg)("h2",{id:"full-request-analysis"},"Full request analysis"),(0,i.yg)("p",null,"The operation complexity analyzer can also take arguments into account when analyzing operation complexity."),(0,i.yg)("p",null,"If we look at our data graph, we can see that the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field actually has an argument\nthat defines how many books are returned. The ",(0,i.yg)("inlineCode",{parentName:"p"},"take")," argument, in this case, specifies\nthe maximum books that the field will return."),(0,i.yg)("p",null,"When measuring the field","`","s impact, we can take the argument ",(0,i.yg)("inlineCode",{parentName:"p"},"take")," into account as a\nmultiplier of our cost. This means we might want to lower the cost to ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"take")," argument."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"With the multiplier in place, we now get a cost of ",(0,i.yg)("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.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"10 * (5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.yg)("p",null,"When drilling in further, the cost will go up to ",(0,i.yg)("inlineCode",{parentName:"p"},"240")," since we are now pulling twice as much books and also their authors."),(0,i.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"20 * (5 + 1 + 5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: 20) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("p",null,"Notice the nullable ",(0,i.yg)("inlineCode",{parentName:"p"},"$take")," parameter. This might come in handy if ",(0,i.yg)("inlineCode",{parentName:"p"},"take: null"),' means "get all items",\nbut that would also mean that the overall complexity would only be ',(0,i.yg)("inlineCode",{parentName:"p"},"1 + 5 + 1 + 5 + 1 = 11"),",\nwhen in fact that would be a very costly query to execute. "),(0,i.yg)("p",null,"If all of the multiplier fields are either ",(0,i.yg)("inlineCode",{parentName:"p"},"null")," or missing (and don't have default values),\n",(0,i.yg)("inlineCode",{parentName:"p"},"defaultMultiplier")," is used:"),(0,i.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"200 * (5 + 1 + 5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: null) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("h2",{id:"setup"},"Setup"),(0,i.yg)("p",null,"As with query depth, automatic query complexity is configured through PSR15 middleware:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Beware that introspection queries would also be limited in complexity. A full introspection\nquery sits at around ",(0,i.yg)("inlineCode",{parentName:"p"},"107")," points, so we recommend a minimum of ",(0,i.yg)("inlineCode",{parentName:"p"},"150")," for query complexity limit."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2960],{10976:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>l,default:()=>h,frontMatter:()=>o,metadata:()=>r,toc:()=>s});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:t,...n}=e;return(0,i.yg)(y,(0,a.A)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("h2",{id:"query-depth"},"Query depth"),(0,i.yg)("p",null,"The simplest way to limit complexity is to limit the max query depth. ",(0,i.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php"),",\nwhich GraphQLite relies on, ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"addValidationRule")," when building your PSR15 middleware:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$builder->addValidationRule(new \\GraphQL\\Validator\\Rules\\QueryDepth(7));\n")),(0,i.yg)("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.yg)("h2",{id:"static-request-analysis"},"Static request analysis"),(0,i.yg)("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.yg)("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.yg)("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.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the above example executing the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field on the ",(0,i.yg)("inlineCode",{parentName:"p"},"Query")," type might go to the\ndatabase and fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"Book"),". This means that the cost of the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field is\nprobably higher than the cost of the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"title"),", the default\ncost of ",(0,i.yg)("inlineCode",{parentName:"p"},"1")," os OK. But for ",(0,i.yg)("inlineCode",{parentName:"p"},"books"),", we might want to go with a higher cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"10"),"\nsince we are getting a list of books from our database."),(0,i.yg)("p",null,"Moreover, we have the field ",(0,i.yg)("inlineCode",{parentName:"p"},"author")," on the book, which might go to the database\nas well to fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"Author")," object. Since we are only fetching a single item here,\nwe might want to apply a cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"5")," to this field."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"If we run the following query against our data graph, we will come up with the cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"11"),"."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.yg)("p",null,"When drilling in further, a cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"17")," occurs."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"10")," even though we might get one or one\nhundred books back?"),(0,i.yg)("h2",{id:"full-request-analysis"},"Full request analysis"),(0,i.yg)("p",null,"The operation complexity analyzer can also take arguments into account when analyzing operation complexity."),(0,i.yg)("p",null,"If we look at our data graph, we can see that the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field actually has an argument\nthat defines how many books are returned. The ",(0,i.yg)("inlineCode",{parentName:"p"},"take")," argument, in this case, specifies\nthe maximum books that the field will return."),(0,i.yg)("p",null,"When measuring the field","`","s impact, we can take the argument ",(0,i.yg)("inlineCode",{parentName:"p"},"take")," into account as a\nmultiplier of our cost. This means we might want to lower the cost to ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"take")," argument."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"With the multiplier in place, we now get a cost of ",(0,i.yg)("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.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"10 * (5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.yg)("p",null,"When drilling in further, the cost will go up to ",(0,i.yg)("inlineCode",{parentName:"p"},"240")," since we are now pulling twice as much books and also their authors."),(0,i.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"20 * (5 + 1 + 5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: 20) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("p",null,"Notice the nullable ",(0,i.yg)("inlineCode",{parentName:"p"},"$take")," parameter. This might come in handy if ",(0,i.yg)("inlineCode",{parentName:"p"},"take: null"),' means "get all items",\nbut that would also mean that the overall complexity would only be ',(0,i.yg)("inlineCode",{parentName:"p"},"1 + 5 + 1 + 5 + 1 = 11"),",\nwhen in fact that would be a very costly query to execute. "),(0,i.yg)("p",null,"If all of the multiplier fields are either ",(0,i.yg)("inlineCode",{parentName:"p"},"null")," or missing (and don't have default values),\n",(0,i.yg)("inlineCode",{parentName:"p"},"defaultMultiplier")," is used:"),(0,i.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"200 * (5 + 1 + 5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: null) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("h2",{id:"setup"},"Setup"),(0,i.yg)("p",null,"As with query depth, automatic query complexity is configured through PSR15 middleware:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Beware that introspection queries would also be limited in complexity. A full introspection\nquery sits at around ",(0,i.yg)("inlineCode",{parentName:"p"},"107")," points, so we recommend a minimum of ",(0,i.yg)("inlineCode",{parentName:"p"},"150")," for query complexity limit."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/64947e00.dcd10efb.js b/assets/js/64947e00.75fbabf5.js similarity index 99% rename from assets/js/64947e00.dcd10efb.js rename to assets/js/64947e00.75fbabf5.js index 355f5f90a..de06273eb 100644 --- a/assets/js/64947e00.dcd10efb.js +++ b/assets/js/64947e00.75fbabf5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8722],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),l=n(20053);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.A)(r.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>T});var a=n(58168),l=n(96540),r=n(20053),i=n(23104),o=n(56347),u=n(57485),p=n(31682),s=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function g(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.W6)(),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.aZ)(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 m(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(!y({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]=g({queryString:n,groupId:a}),[c,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Dv)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),h=(()=>{const e=u??c;return y({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),m(e)}),[p,m,r]),tabValues:r}}var h=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},y=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.A)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},i,{className:(0,r.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(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 I(e){const t=m(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,t)),l.createElement(v,(0,a.A)({},e,t)))}function T(e){const t=(0,h.A)();return l.createElement(I,(0,a.A)({key:String(t)},e))}},27373:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>g,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(58168),l=(n(96540),n(15680)),r=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function g(e){let{components:t,...n}=e;return(0,l.yg)(y,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.yg)("p",null,"Your GraphQL query might look like this:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,l.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using ",(0,l.yg)("strong",{parentName:"p"},"Factory")," or annotating the class with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input"),"."),(0,l.yg)("h2",{id:"factory"},"Factory"),(0,l.yg)("p",null,"A ",(0,l.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.yg)("p",null,"Here is an example of factory:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.yg)("p",null,"A few important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.yg)("p",null,"You can use the ",(0,l.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.yg)("p",null,"Here is an annotated sample:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("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.yg)("p",null,"Image your ",(0,l.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"With the ",(0,l.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.yg)("p",null,"To be able to hide an argument, the argument must have a default value."),(0,l.yg)("h2",{id:"input-annotation"},"@Input Annotation"),(0,l.yg)("p",null,"Let's transform ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," class into an input type by adding ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation to it and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to corresponding properties:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"Now if you call ",(0,l.yg)("inlineCode",{parentName:"p"},"getCities()")," query you can pass the location input in the same way as with factories.\nThe ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with provided ",(0,l.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.yg)("inlineCode",{parentName:"p"},"longitude")," and passed to the controller as a parameter."),(0,l.yg)("p",null,"There are some important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized only on properties for Input Type."),(0,l.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.yg)("ul",{parentName:"li"},(0,l.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort."),(0,l.yg)("li",{parentName:"ul"},"For private or protected properties implemented public setter is required (if they are not set via constructor). For example ",(0,l.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),".")))),(0,l.yg)("h3",{id:"multiple-input-types-per-one-class"},"Multiple input types per one class"),(0,l.yg)("p",null,"Simple usage of ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"There are 2 input types created for just one class: ",(0,l.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.yg)("p",null,"Note that ",(0,l.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.yg)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.yg)("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."))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8722],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),l=n(20053);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.A)(r.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>T});var a=n(58168),l=n(96540),r=n(20053),i=n(23104),o=n(56347),u=n(57485),p=n(31682),s=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function g(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.W6)(),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.aZ)(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 m(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(!y({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]=g({queryString:n,groupId:a}),[c,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Dv)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),h=(()=>{const e=u??c;return y({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),m(e)}),[p,m,r]),tabValues:r}}var h=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},y=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.A)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},i,{className:(0,r.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(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 I(e){const t=m(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,t)),l.createElement(v,(0,a.A)({},e,t)))}function T(e){const t=(0,h.A)();return l.createElement(I,(0,a.A)({key:String(t)},e))}},27373:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>g,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(58168),l=(n(96540),n(15680)),r=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function g(e){let{components:t,...n}=e;return(0,l.yg)(y,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.yg)("p",null,"Your GraphQL query might look like this:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,l.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using ",(0,l.yg)("strong",{parentName:"p"},"Factory")," or annotating the class with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input"),"."),(0,l.yg)("h2",{id:"factory"},"Factory"),(0,l.yg)("p",null,"A ",(0,l.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.yg)("p",null,"Here is an example of factory:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.yg)("p",null,"A few important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.yg)("p",null,"You can use the ",(0,l.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.yg)("p",null,"Here is an annotated sample:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("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.yg)("p",null,"Image your ",(0,l.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"With the ",(0,l.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.yg)("p",null,"To be able to hide an argument, the argument must have a default value."),(0,l.yg)("h2",{id:"input-annotation"},"@Input Annotation"),(0,l.yg)("p",null,"Let's transform ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," class into an input type by adding ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation to it and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to corresponding properties:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"Now if you call ",(0,l.yg)("inlineCode",{parentName:"p"},"getCities()")," query you can pass the location input in the same way as with factories.\nThe ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with provided ",(0,l.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.yg)("inlineCode",{parentName:"p"},"longitude")," and passed to the controller as a parameter."),(0,l.yg)("p",null,"There are some important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized only on properties for Input Type."),(0,l.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.yg)("ul",{parentName:"li"},(0,l.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort."),(0,l.yg)("li",{parentName:"ul"},"For private or protected properties implemented public setter is required (if they are not set via constructor). For example ",(0,l.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),".")))),(0,l.yg)("h3",{id:"multiple-input-types-per-one-class"},"Multiple input types per one class"),(0,l.yg)("p",null,"Simple usage of ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"There are 2 input types created for just one class: ",(0,l.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.yg)("p",null,"Note that ",(0,l.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.yg)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.yg)("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."))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/652c74f1.6f8e2dfd.js b/assets/js/652c74f1.8f6d89ec.js similarity index 99% rename from assets/js/652c74f1.6f8e2dfd.js rename to assets/js/652c74f1.8f6d89ec.js index 2b4a25957..1ec343af1 100644 --- a/assets/js/652c74f1.6f8e2dfd.js +++ b/assets/js/652c74f1.8f6d89ec.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[211],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),i=n(56347),s=n(57485),u=n(31682),p=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.W6)(),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.aZ)(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),[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]=y({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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),m=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);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 m=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":i===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 T(e){const t=g(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},21807:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 y(e){let{components:t,...i}=e;return(0,r.yg)(h,(0,a.A)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.yg)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.yg)("p",null,"Read the ",(0,r.yg)("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.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:n(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}y.isMDXComponent=!0},67258:(e,t,n)=>{n.d(t,{A:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[211],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),i=n(56347),s=n(57485),u=n(31682),p=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.W6)(),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.aZ)(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),[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]=y({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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),m=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);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 m=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":i===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 T(e){const t=g(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},21807:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 y(e){let{components:t,...i}=e;return(0,r.yg)(h,(0,a.A)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.yg)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.yg)("p",null,"Read the ",(0,r.yg)("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.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:n(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}y.isMDXComponent=!0},67258:(e,t,n)=>{n.d(t,{A:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/65b8d1d1.be427580.js b/assets/js/65b8d1d1.2e0aa238.js similarity index 99% rename from assets/js/65b8d1d1.be427580.js rename to assets/js/65b8d1d1.2e0aa238.js index 53fc030c5..100312e1c 100644 --- a/assets/js/65b8d1d1.be427580.js +++ b/assets/js/65b8d1d1.2e0aa238.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4330],{6299:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>l,default:()=>h,frontMatter:()=>o,metadata:()=>r,toc:()=>s});var a=n(58168),i=(n(96540),n(15680));n(67443);const o={id:"operation-complexity",title:"Operation complexity",sidebar_label:"Operation complexity"},l=void 0,r={unversionedId:"operation-complexity",id:"version-7.0.0/operation-complexity",title:"Operation complexity",description:"At some point you may find yourself receiving queries with an insane amount of requested",source:"@site/versioned_docs/version-7.0.0/operation-complexity.md",sourceDirName:".",slug:"/operation-complexity",permalink:"/docs/7.0.0/operation-complexity",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/operation-complexity.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"operation-complexity",title:"Operation complexity",sidebar_label:"Operation complexity"},sidebar:"docs",previous:{title:"Connecting security to your framework",permalink:"/docs/7.0.0/implementing-security"},next:{title:"Query plan",permalink:"/docs/7.0.0/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},y="wrapper";function h(e){let{components:t,...n}=e;return(0,i.yg)(y,(0,a.A)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("h2",{id:"query-depth"},"Query depth"),(0,i.yg)("p",null,"The simplest way to limit complexity is to limit the max query depth. ",(0,i.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php"),",\nwhich GraphQLite relies on, ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"addValidationRule")," when building your PSR15 middleware:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$builder->addValidationRule(new \\GraphQL\\Validator\\Rules\\QueryDepth(7));\n")),(0,i.yg)("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.yg)("h2",{id:"static-request-analysis"},"Static request analysis"),(0,i.yg)("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.yg)("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.yg)("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.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the above example executing the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field on the ",(0,i.yg)("inlineCode",{parentName:"p"},"Query")," type might go to the\ndatabase and fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"Book"),". This means that the cost of the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field is\nprobably higher than the cost of the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"title"),", the default\ncost of ",(0,i.yg)("inlineCode",{parentName:"p"},"1")," os OK. But for ",(0,i.yg)("inlineCode",{parentName:"p"},"books"),", we might want to go with a higher cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"10"),"\nsince we are getting a list of books from our database."),(0,i.yg)("p",null,"Moreover, we have the field ",(0,i.yg)("inlineCode",{parentName:"p"},"author")," on the book, which might go to the database\nas well to fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"Author")," object. Since we are only fetching a single item here,\nwe might want to apply a cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"5")," to this field."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"If we run the following query against our data graph, we will come up with the cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"11"),"."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.yg)("p",null,"When drilling in further, a cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"17")," occurs."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"10")," even though we might get one or one\nhundred books back?"),(0,i.yg)("h2",{id:"full-request-analysis"},"Full request analysis"),(0,i.yg)("p",null,"The operation complexity analyzer can also take arguments into account when analyzing operation complexity."),(0,i.yg)("p",null,"If we look at our data graph, we can see that the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field actually has an argument\nthat defines how many books are returned. The ",(0,i.yg)("inlineCode",{parentName:"p"},"take")," argument, in this case, specifies\nthe maximum books that the field will return."),(0,i.yg)("p",null,"When measuring the field","`","s impact, we can take the argument ",(0,i.yg)("inlineCode",{parentName:"p"},"take")," into account as a\nmultiplier of our cost. This means we might want to lower the cost to ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"take")," argument."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"With the multiplier in place, we now get a cost of ",(0,i.yg)("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.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"10 * (5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.yg)("p",null,"When drilling in further, the cost will go up to ",(0,i.yg)("inlineCode",{parentName:"p"},"240")," since we are now pulling twice as much books and also their authors."),(0,i.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"20 * (5 + 1 + 5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: 20) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("p",null,"Notice the nullable ",(0,i.yg)("inlineCode",{parentName:"p"},"$take")," parameter. This might come in handy if ",(0,i.yg)("inlineCode",{parentName:"p"},"take: null"),' means "get all items",\nbut that would also mean that the overall complexity would only be ',(0,i.yg)("inlineCode",{parentName:"p"},"1 + 5 + 1 + 5 + 1 = 11"),",\nwhen in fact that would be a very costly query to execute. "),(0,i.yg)("p",null,"If all of the multiplier fields are either ",(0,i.yg)("inlineCode",{parentName:"p"},"null")," or missing (and don't have default values),\n",(0,i.yg)("inlineCode",{parentName:"p"},"defaultMultiplier")," is used:"),(0,i.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"200 * (5 + 1 + 5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: null) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("h2",{id:"setup"},"Setup"),(0,i.yg)("p",null,"As with query depth, automatic query complexity is configured through PSR15 middleware:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Beware that introspection queries would also be limited in complexity. A full introspection\nquery sits at around ",(0,i.yg)("inlineCode",{parentName:"p"},"107")," points, so we recommend a minimum of ",(0,i.yg)("inlineCode",{parentName:"p"},"150")," for query complexity limit."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4330],{6299:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>l,default:()=>h,frontMatter:()=>o,metadata:()=>r,toc:()=>s});var a=n(58168),i=(n(96540),n(15680));n(67443);const o={id:"operation-complexity",title:"Operation complexity",sidebar_label:"Operation complexity"},l=void 0,r={unversionedId:"operation-complexity",id:"version-7.0.0/operation-complexity",title:"Operation complexity",description:"At some point you may find yourself receiving queries with an insane amount of requested",source:"@site/versioned_docs/version-7.0.0/operation-complexity.md",sourceDirName:".",slug:"/operation-complexity",permalink:"/docs/7.0.0/operation-complexity",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/operation-complexity.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"operation-complexity",title:"Operation complexity",sidebar_label:"Operation complexity"},sidebar:"docs",previous:{title:"Connecting security to your framework",permalink:"/docs/7.0.0/implementing-security"},next:{title:"Query plan",permalink:"/docs/7.0.0/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},y="wrapper";function h(e){let{components:t,...n}=e;return(0,i.yg)(y,(0,a.A)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("h2",{id:"query-depth"},"Query depth"),(0,i.yg)("p",null,"The simplest way to limit complexity is to limit the max query depth. ",(0,i.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php"),",\nwhich GraphQLite relies on, ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"addValidationRule")," when building your PSR15 middleware:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$builder->addValidationRule(new \\GraphQL\\Validator\\Rules\\QueryDepth(7));\n")),(0,i.yg)("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.yg)("h2",{id:"static-request-analysis"},"Static request analysis"),(0,i.yg)("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.yg)("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.yg)("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.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the above example executing the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field on the ",(0,i.yg)("inlineCode",{parentName:"p"},"Query")," type might go to the\ndatabase and fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"Book"),". This means that the cost of the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field is\nprobably higher than the cost of the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"title"),", the default\ncost of ",(0,i.yg)("inlineCode",{parentName:"p"},"1")," os OK. But for ",(0,i.yg)("inlineCode",{parentName:"p"},"books"),", we might want to go with a higher cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"10"),"\nsince we are getting a list of books from our database."),(0,i.yg)("p",null,"Moreover, we have the field ",(0,i.yg)("inlineCode",{parentName:"p"},"author")," on the book, which might go to the database\nas well to fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"Author")," object. Since we are only fetching a single item here,\nwe might want to apply a cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"5")," to this field."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"If we run the following query against our data graph, we will come up with the cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"11"),"."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.yg)("p",null,"When drilling in further, a cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"17")," occurs."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"10")," even though we might get one or one\nhundred books back?"),(0,i.yg)("h2",{id:"full-request-analysis"},"Full request analysis"),(0,i.yg)("p",null,"The operation complexity analyzer can also take arguments into account when analyzing operation complexity."),(0,i.yg)("p",null,"If we look at our data graph, we can see that the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field actually has an argument\nthat defines how many books are returned. The ",(0,i.yg)("inlineCode",{parentName:"p"},"take")," argument, in this case, specifies\nthe maximum books that the field will return."),(0,i.yg)("p",null,"When measuring the field","`","s impact, we can take the argument ",(0,i.yg)("inlineCode",{parentName:"p"},"take")," into account as a\nmultiplier of our cost. This means we might want to lower the cost to ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"take")," argument."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"With the multiplier in place, we now get a cost of ",(0,i.yg)("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.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"10 * (5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.yg)("p",null,"When drilling in further, the cost will go up to ",(0,i.yg)("inlineCode",{parentName:"p"},"240")," since we are now pulling twice as much books and also their authors."),(0,i.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"20 * (5 + 1 + 5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: 20) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("p",null,"Notice the nullable ",(0,i.yg)("inlineCode",{parentName:"p"},"$take")," parameter. This might come in handy if ",(0,i.yg)("inlineCode",{parentName:"p"},"take: null"),' means "get all items",\nbut that would also mean that the overall complexity would only be ',(0,i.yg)("inlineCode",{parentName:"p"},"1 + 5 + 1 + 5 + 1 = 11"),",\nwhen in fact that would be a very costly query to execute. "),(0,i.yg)("p",null,"If all of the multiplier fields are either ",(0,i.yg)("inlineCode",{parentName:"p"},"null")," or missing (and don't have default values),\n",(0,i.yg)("inlineCode",{parentName:"p"},"defaultMultiplier")," is used:"),(0,i.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"200 * (5 + 1 + 5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: null) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("h2",{id:"setup"},"Setup"),(0,i.yg)("p",null,"As with query depth, automatic query complexity is configured through PSR15 middleware:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Beware that introspection queries would also be limited in complexity. A full introspection\nquery sits at around ",(0,i.yg)("inlineCode",{parentName:"p"},"107")," points, so we recommend a minimum of ",(0,i.yg)("inlineCode",{parentName:"p"},"150")," for query complexity limit."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/673df5d6.c3b07156.js b/assets/js/673df5d6.7f16b068.js similarity index 99% rename from assets/js/673df5d6.c3b07156.js rename to assets/js/673df5d6.7f16b068.js index d81bea7e7..13994d35c 100644 --- a/assets/js/673df5d6.c3b07156.js +++ b/assets/js/673df5d6.7f16b068.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7326],{41295:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var r=n(58168),t=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function d(e){let{components:a,...n}=e;return(0,t.yg)(h,(0,r.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,t.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,t.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,t.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,t.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,t.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,t.yg)("p",null,"You can then configure the library by editing ",(0,t.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/graphqlite.php")),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The debug parameters are detailed in the ",(0,t.yg)("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,t.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,t.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,t.yg)("code",null,"/graphql")," route is placed under ",(0,t.yg)("code",null,"web")," middleware group which requires a",(0,t.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,t.yg)("p",null,"You have 3 options:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"Use the ",(0,t.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,t.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,t.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,t.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,t.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,t.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,t.yg)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,t.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,t.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/graphqlite.php")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,t.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,t.yg)("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,t.yg)("p",null,"Simply add ",(0,t.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,t.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,t.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,t.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,t.yg)("p",null,"If you are planning to use ",(0,t.yg)("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,t.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,t.yg)("p",null,"Assuming you are using ",(0,t.yg)("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,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"Sample Apollo client setup with CSRF support")),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,t.yg)("p",null,"By default, the playground will be available at ",(0,t.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,t.yg)("p",null,"Or you can install ",(0,t.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,t.yg)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,t.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,t.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,t.yg)("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,t.yg)("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([[7326],{41295:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var r=n(58168),t=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function d(e){let{components:a,...n}=e;return(0,t.yg)(h,(0,r.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,t.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,t.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,t.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,t.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,t.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,t.yg)("p",null,"You can then configure the library by editing ",(0,t.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/graphqlite.php")),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The debug parameters are detailed in the ",(0,t.yg)("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,t.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,t.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,t.yg)("code",null,"/graphql")," route is placed under ",(0,t.yg)("code",null,"web")," middleware group which requires a",(0,t.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,t.yg)("p",null,"You have 3 options:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"Use the ",(0,t.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,t.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,t.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,t.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,t.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,t.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,t.yg)("p",null,"If you plan to use graphql for server-to-server connection only, you should probably configure GraphQLite to use the\n",(0,t.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,t.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/graphqlite.php")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,t.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,t.yg)("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,t.yg)("p",null,"Simply add ",(0,t.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,t.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,t.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,t.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,t.yg)("p",null,"If you are planning to use ",(0,t.yg)("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,t.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,t.yg)("p",null,"Assuming you are using ",(0,t.yg)("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,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"Sample Apollo client setup with CSRF support")),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,t.yg)("p",null,"By default, the playground will be available at ",(0,t.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,t.yg)("p",null,"Or you can install ",(0,t.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,t.yg)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,t.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,t.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,t.yg)("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,t.yg)("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/68b7d615.460d30f2.js b/assets/js/68b7d615.06b7671d.js similarity index 99% rename from assets/js/68b7d615.460d30f2.js rename to assets/js/68b7d615.06b7671d.js index a3399cb31..b3e2fe7a0 100644 --- a/assets/js/68b7d615.460d30f2.js +++ b/assets/js/68b7d615.06b7671d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[436],{63881:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>o,toc:()=>g});var n=a(58168),l=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],y={toc:g},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.yg)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.yg)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("a",{parentName:"td",href:"/docs/5.0/external-type-declaration"},"the class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("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.yg)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/5.0/extend-type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"input-annotation"},"@Input annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true")," if name is not specified. Whether the annotated PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"update"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.yg)("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.yg)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.yg)("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.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"for"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string, array"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/5.0/input-types"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.yg)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"value"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("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.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[436],{63881:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>o,toc:()=>g});var n=a(58168),l=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],y={toc:g},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.yg)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.yg)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("a",{parentName:"td",href:"/docs/5.0/external-type-declaration"},"the class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("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.yg)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/5.0/extend-type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"input-annotation"},"@Input annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotation is used to declare a GraphQL input type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true")," if name is not specified. Whether the annotated PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"update"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,l.yg)("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.yg)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," or ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,l.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,l.yg)("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.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"for"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string, array"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/5.0/input-types"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,l.yg)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/5.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"description"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,l.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"value"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("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.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/68e30702.6ad10b96.js b/assets/js/68e30702.2c897d24.js similarity index 99% rename from assets/js/68e30702.6ad10b96.js rename to assets/js/68e30702.2c897d24.js index 194a00745..a0fd637ec 100644 --- a/assets/js/68e30702.6ad10b96.js +++ b/assets/js/68e30702.2c897d24.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3468],{19365:(e,t,n)=>{n.d(t,{A:()=>l});var a=n(96540),r=n(20053);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.A)(s.tabItem,l),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),s=n(20053),l=n(23104),o=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),y=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);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 y=n(92303);const b={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.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.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 T(e){const t=f(e);return r.createElement("div",{className:(0,s.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,y.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},46732:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),s=(n(67443),n(11470)),l=n(19365);const o={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,u={unversionedId:"prefetch-method",id:"version-7.0.0/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-7.0.0/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/7.0.0/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/prefetch-method.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"docs",previous:{title:"Query plan",permalink:"/docs/7.0.0/query-plan"},next:{title:"Automatic persisted queries",permalink:"/docs/7.0.0/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.yg)(d,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/7.0.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a static method in the same class: ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Prefetch('prefetchMethod')]")),(0,r.yg)("li",{parentName:"ul"},"a static method in a different class: ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Prefetch([OtherClass::class, 'prefetchMethod')]")),(0,r.yg)("li",{parentName:"ul"},"a non-static method in a different class, resolvable through the container: ",(0,r.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetch methods."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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([[3468],{19365:(e,t,n)=>{n.d(t,{A:()=>l});var a=n(96540),r=n(20053);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.A)(s.tabItem,l),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),s=n(20053),l=n(23104),o=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&s.set(e)}),[n,s])]}({groupId:a}),y=(()=>{const e=i??p;return d({value:e,tabValues:s})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);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 y=n(92303);const b={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.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.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 T(e){const t=f(e);return r.createElement("div",{className:(0,s.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,y.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},46732:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),s=(n(67443),n(11470)),l=n(19365);const o={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,u={unversionedId:"prefetch-method",id:"version-7.0.0/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-7.0.0/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/7.0.0/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/prefetch-method.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"docs",previous:{title:"Query plan",permalink:"/docs/7.0.0/query-plan"},next:{title:"Automatic persisted queries",permalink:"/docs/7.0.0/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.yg)(d,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/7.0.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a static method in the same class: ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Prefetch('prefetchMethod')]")),(0,r.yg)("li",{parentName:"ul"},"a static method in a different class: ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Prefetch([OtherClass::class, 'prefetchMethod')]")),(0,r.yg)("li",{parentName:"ul"},"a non-static method in a different class, resolvable through the container: ",(0,r.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetch methods."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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/69f2ab1f.101a90d5.js b/assets/js/69f2ab1f.1faf5012.js similarity index 99% rename from assets/js/69f2ab1f.101a90d5.js rename to assets/js/69f2ab1f.1faf5012.js index 20fee900b..be0aa3162 100644 --- a/assets/js/69f2ab1f.101a90d5.js +++ b/assets/js/69f2ab1f.1faf5012.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2784],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),s=a(56347),i=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),h(e)}),[u,h,l]),tabValues:l}}var f=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},g=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},o,{className:(0,l.A)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":s===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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},93276:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(g,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"You will need to install the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"In your query, simply return a class that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.yg)("p",null,'The "count" field returns the ',(0,r.yg)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2784],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),s=a(56347),i=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),h(e)}),[u,h,l]),tabValues:l}}var f=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},g=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},o,{className:(0,l.A)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":s===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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},93276:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(g,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"You will need to install the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"In your query, simply return a class that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.yg)("p",null,'The "count" field returns the ',(0,r.yg)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6a8c9872.7b918e26.js b/assets/js/6a8c9872.8c4f08ae.js similarity index 99% rename from assets/js/6a8c9872.7b918e26.js rename to assets/js/6a8c9872.8c4f08ae.js index 0b059d3e2..ceb2ca0f6 100644 --- a/assets/js/6a8c9872.7b918e26.js +++ b/assets/js/6a8c9872.8c4f08ae.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8087],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>q});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),u=n(56347),s=n(57485),i=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&u(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}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":u===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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function q(e){const t=(0,y.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},74433:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);const u={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},s=void 0,i={unversionedId:"query-plan",id:"version-7.0.0/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-7.0.0/query-plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/7.0.0/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/query-plan.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"docs",previous:{title:"Operation complexity",permalink:"/docs/7.0.0/operation-complexity"},next:{title:"Prefetching records",permalink:"/docs/7.0.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.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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([[8087],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>q});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),u=n(56347),s=n(57485),i=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&u(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}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":u===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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function q(e){const t=(0,y.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},74433:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);const u={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},s=void 0,i={unversionedId:"query-plan",id:"version-7.0.0/query-plan",title:"Query plan",description:"The problem",source:"@site/versioned_docs/version-7.0.0/query-plan.mdx",sourceDirName:".",slug:"/query-plan",permalink:"/docs/7.0.0/query-plan",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/query-plan.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},sidebar:"docs",previous:{title:"Operation complexity",permalink:"/docs/7.0.0/operation-complexity"},next:{title:"Prefetching records",permalink:"/docs/7.0.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.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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/6ad31330.6147159c.js b/assets/js/6ad31330.e5c9ae06.js similarity index 97% rename from assets/js/6ad31330.6147159c.js rename to assets/js/6ad31330.e5c9ae06.js index e8bb323e9..dc806e6bd 100644 --- a/assets/js/6ad31330.6147159c.js +++ b/assets/js/6ad31330.e5c9ae06.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6730],{8119:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:l},g="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,r.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6730],{8119:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:l},g="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,r.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6b4e0fb4.972829be.js b/assets/js/6b4e0fb4.af536444.js similarity index 99% rename from assets/js/6b4e0fb4.972829be.js rename to assets/js/6b4e0fb4.af536444.js index c55f0e207..b50847995 100644 --- a/assets/js/6b4e0fb4.972829be.js +++ b/assets/js/6b4e0fb4.af536444.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4086],{37596:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>i,default:()=>d,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var r=t(58168),o=(t(96540),t(15680));t(67443);const a={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},i=void 0,s={unversionedId:"error-handling",id:"version-8.0.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-8.0.0/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-8.0.0/error-handling.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},p={},l=[{value:"HTTP response code",id:"http-response-code",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:l},h="wrapper";function d(e){let{components:n,...t}=e;return(0,o.yg)(h,(0,r.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,o.yg)("pre",null,(0,o.yg)("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 }\n ]\n}\n')),(0,o.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,o.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,o.yg)("p",null,"By default, when you throw a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,o.yg)("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.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,o.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,o.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,o.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,o.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,o.yg)("p",null,"will generate:"),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "field": "name"\n }\n }\n ]\n}\n')),(0,o.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,o.yg)("p",null,"Rather that throwing the base ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,o.yg)("p",null,"Any exception that implements interface ",(0,o.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,o.yg)("pre",null,(0,o.yg)("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 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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,o.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,o.yg)("pre",null,(0,o.yg)("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,o.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,o.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,o.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,o.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,o.yg)("p",null,"Actually, the ",(0,o.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,o.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,o.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,o.yg)("p",null,"If an exception that does not implement ",(0,o.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,o.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,o.yg)("p",null,"You can ",(0,o.yg)("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.yg)("a",{parentName:"p",href:"/docs/symfony-bundle"},"Symfony"),", ",(0,o.yg)("a",{parentName:"p",href:"/docs/laravel-package"},"Laravel"),")."),(0,o.yg)("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([[4086],{37596:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>i,default:()=>d,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var r=t(58168),o=(t(96540),t(15680));t(67443);const a={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},i=void 0,s={unversionedId:"error-handling",id:"version-8.0.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-8.0.0/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-8.0.0/error-handling.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},p={},l=[{value:"HTTP response code",id:"http-response-code",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:l},h="wrapper";function d(e){let{components:n,...t}=e;return(0,o.yg)(h,(0,r.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,o.yg)("pre",null,(0,o.yg)("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 }\n ]\n}\n')),(0,o.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,o.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,o.yg)("p",null,"By default, when you throw a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,o.yg)("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.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,o.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,o.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,o.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,o.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,o.yg)("p",null,"will generate:"),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "field": "name"\n }\n }\n ]\n}\n')),(0,o.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,o.yg)("p",null,"Rather that throwing the base ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,o.yg)("p",null,"Any exception that implements interface ",(0,o.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,o.yg)("pre",null,(0,o.yg)("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 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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,o.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,o.yg)("pre",null,(0,o.yg)("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,o.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,o.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,o.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,o.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,o.yg)("p",null,"Actually, the ",(0,o.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,o.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,o.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,o.yg)("p",null,"If an exception that does not implement ",(0,o.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,o.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,o.yg)("p",null,"You can ",(0,o.yg)("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.yg)("a",{parentName:"p",href:"/docs/symfony-bundle"},"Symfony"),", ",(0,o.yg)("a",{parentName:"p",href:"/docs/laravel-package"},"Laravel"),")."),(0,o.yg)("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/6c124661.6c7f6118.js b/assets/js/6c124661.4af7f962.js similarity index 98% rename from assets/js/6c124661.6c7f6118.js rename to assets/js/6c124661.4af7f962.js index 66d2a46ca..2e8ae6323 100644 --- a/assets/js/6c124661.6c7f6118.js +++ b/assets/js/6c124661.4af7f962.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5762],{47935:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>n,default:()=>h,frontMatter:()=>i,metadata:()=>r,toc:()=>s});var o=t(58168),l=(t(96540),t(15680));t(67443);const i={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},n=void 0,r={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},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:a,...t}=e;return(0,l.yg)(d,(0,o.A)({},u,t,{components:a,mdxType:"MDXLayout"}),(0,l.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,l.yg)("h2",{id:"installation"},"Installation"),(0,l.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,l.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,l.yg)("p",null,"You must start by installing this package:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,l.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,l.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,l.yg)("p",null,"In order to use this, you must first be sure that the ",(0,l.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,l.yg)("p",null,"Simply add ",(0,l.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,l.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,l.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,l.yg)("h2",{id:"usage"},"Usage"),(0,l.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,l.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,l.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,l.yg)("pre",null,(0,l.yg)("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([[5762],{47935:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>n,default:()=>h,frontMatter:()=>i,metadata:()=>r,toc:()=>s});var o=t(58168),l=(t(96540),t(15680));t(67443);const i={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},n=void 0,r={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},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:a,...t}=e;return(0,l.yg)(d,(0,o.A)({},u,t,{components:a,mdxType:"MDXLayout"}),(0,l.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,l.yg)("h2",{id:"installation"},"Installation"),(0,l.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,l.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,l.yg)("p",null,"You must start by installing this package:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,l.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,l.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,l.yg)("p",null,"In order to use this, you must first be sure that the ",(0,l.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,l.yg)("p",null,"Simply add ",(0,l.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,l.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,l.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,l.yg)("h2",{id:"usage"},"Usage"),(0,l.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,l.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,l.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,l.yg)("pre",null,(0,l.yg)("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.3e308cd7.js b/assets/js/6c14a231.cd87becb.js similarity index 99% rename from assets/js/6c14a231.3e308cd7.js rename to assets/js/6c14a231.cd87becb.js index e6a4f38dc..806a688ee 100644 --- a/assets/js/6c14a231.3e308cd7.js +++ b/assets/js/6c14a231.cd87becb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1188],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(l.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),l=a(20053),u=a(23104),o=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.W6)(),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.aZ)(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 h(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]=g({queryString:a,groupId:n}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);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),h(e)}),[i,h,l]),tabValues:l}}var b=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.tabItem,u?.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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(f,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function T(e){const t=(0,b.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},81087:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},p=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1188],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(l.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),l=a(20053),u=a(23104),o=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.W6)(),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.aZ)(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 h(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]=g({queryString:a,groupId:n}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);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),h(e)}),[i,h,l]),tabValues:l}}var b=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.tabItem,u?.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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(f,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function T(e){const t=(0,b.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},81087:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},p=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6c4340be.cb8b8de8.js b/assets/js/6c4340be.080987fe.js similarity index 99% rename from assets/js/6c4340be.cb8b8de8.js rename to assets/js/6c4340be.080987fe.js index 482ab355f..2fe55bfb7 100644 --- a/assets/js/6c4340be.cb8b8de8.js +++ b/assets/js/6c4340be.080987fe.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8350],{19365:(e,n,a)=>{a.d(n,{A:()=>r});var t=a(96540),p=a(20053);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:a,className:r}=e;return t.createElement("div",{role:"tabpanel",className:(0,p.A)(l.tabItem,r),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>N});var t=a(58168),p=a(96540),l=a(20053),r=a(23104),s=a(56347),i=a(57485),u=a(31682),o=a(89466);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:a,attributes:t,default:p}}=e;return{value:n,label:a,attributes:t,default:p}}))}function y(e){const{values:n,children:a}=e;return(0,p.useMemo)((()=>{const e=n??c(a);return function(e){const n=(0,u.X)(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,a])}function m(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,i.aZ)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function g(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=y(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!m({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[i,u]=d({queryString:a,groupId:t}),[c,g]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,p.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=i??c;return m({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{h&&s(h)}),[h]);return{selectedValue:r,selectValue:(0,p.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 h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),y=e=>{const n=e.currentTarget,a=o.indexOf(n),t=u[a].value;t!==s&&(c(n),i(t))},m=e=>{let n=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},u.map((e=>{let{value:n,label:a,attributes:r}=e;return p.createElement("li",(0,t.A)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:m,onClick:y},r,{className:(0,l.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function T(e){const n=g(e);return p.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},p.createElement(b,(0,t.A)({},e,n)),p.createElement(v,(0,t.A)({},e,n)))}function N(e){const n=(0,h.A)();return p.createElement(T,(0,t.A)({key:String(n)},e))}},60384:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>i,default:()=>d,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var t=a(58168),p=(a(96540),a(15680)),l=(a(67443),a(11470)),r=a(19365);const s={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},i=void 0,u={unversionedId:"type-mapping",id:"version-7.0.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-7.0.0/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/7.0.0/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/type-mapping.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"docs",previous:{title:"Subscriptions",permalink:"/docs/7.0.0/subscriptions"},next:{title:"Autowiring services",permalink:"/docs/7.0.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}],y={toc:c},m="wrapper";function d(e){let{components:n,...a}=e;return(0,p.yg)(m,(0,t.A)({},y,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/7.0.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/7.0.0/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"Union types for return are supported in GraphQLite as of version 6.0:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"name")," property on the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," annotation:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,p.yg)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,p.yg)("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.yg)("p",null,(0,p.yg)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"name")," argument of the ",(0,p.yg)("inlineCode",{parentName:"p"},"Type")," attribute:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')))),(0,p.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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([[8350],{19365:(e,n,a)=>{a.d(n,{A:()=>r});var t=a(96540),p=a(20053);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:a,className:r}=e;return t.createElement("div",{role:"tabpanel",className:(0,p.A)(l.tabItem,r),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>N});var t=a(58168),p=a(96540),l=a(20053),r=a(23104),s=a(56347),i=a(57485),u=a(31682),o=a(89466);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:a,attributes:t,default:p}}=e;return{value:n,label:a,attributes:t,default:p}}))}function y(e){const{values:n,children:a}=e;return(0,p.useMemo)((()=>{const e=n??c(a);return function(e){const n=(0,u.X)(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,a])}function m(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,i.aZ)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function g(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=y(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!m({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[i,u]=d({queryString:a,groupId:t}),[c,g]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,p.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=i??c;return m({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{h&&s(h)}),[h]);return{selectedValue:r,selectValue:(0,p.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 h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),y=e=>{const n=e.currentTarget,a=o.indexOf(n),t=u[a].value;t!==s&&(c(n),i(t))},m=e=>{let n=null;switch(e.key){case"Enter":y(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},u.map((e=>{let{value:n,label:a,attributes:r}=e;return p.createElement("li",(0,t.A)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:m,onClick:y},r,{className:(0,l.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function T(e){const n=g(e);return p.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},p.createElement(b,(0,t.A)({},e,n)),p.createElement(v,(0,t.A)({},e,n)))}function N(e){const n=(0,h.A)();return p.createElement(T,(0,t.A)({key:String(n)},e))}},60384:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>i,default:()=>d,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var t=a(58168),p=(a(96540),a(15680)),l=(a(67443),a(11470)),r=a(19365);const s={id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},i=void 0,u={unversionedId:"type-mapping",id:"version-7.0.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-7.0.0/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/7.0.0/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/type-mapping.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"docs",previous:{title:"Subscriptions",permalink:"/docs/7.0.0/subscriptions"},next:{title:"Autowiring services",permalink:"/docs/7.0.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}],y={toc:c},m="wrapper";function d(e){let{components:n,...a}=e;return(0,p.yg)(m,(0,t.A)({},y,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/7.0.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/7.0.0/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"Union types for return are supported in GraphQLite as of version 6.0:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"name")," property on the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," annotation:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,p.yg)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,p.yg)("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.yg)("p",null,(0,p.yg)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"name")," argument of the ",(0,p.yg)("inlineCode",{parentName:"p"},"Type")," attribute:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type(name: "UserStatus")]\nclass StatusEnum extends Enum\n{\n // ...\n}\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type(name="UserStatus")\n */\nclass StatusEnum extends Enum\n{\n // ...\n}\n')))),(0,p.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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/6c6ce37c.6a0331a4.js b/assets/js/6c6ce37c.2245fbeb.js similarity index 97% rename from assets/js/6c6ce37c.6a0331a4.js rename to assets/js/6c6ce37c.2245fbeb.js index 53e193e25..ffa211f5a 100644 --- a/assets/js/6c6ce37c.6a0331a4.js +++ b/assets/js/6c6ce37c.2245fbeb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9445],{60388:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9445],{60388:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6c8ff36a.e7a8c20e.js b/assets/js/6c8ff36a.4853c20d.js similarity index 99% rename from assets/js/6c8ff36a.e7a8c20e.js rename to assets/js/6c8ff36a.4853c20d.js index 50de5e85a..a7ff424eb 100644 --- a/assets/js/6c8ff36a.e7a8c20e.js +++ b/assets/js/6c8ff36a.4853c20d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5170],{52072:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>r,default:()=>u,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var t=n(58168),i=(n(96540),n(15680));n(67443);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"version-8.0.0/changelog",title:"Changelog",description:"8.0.0",source:"@site/versioned_docs/version-8.0.0/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/CHANGELOG.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/semver"}},p={},s=[{value:"8.0.0",id:"800",level:2},{value:"Breaking Changes",id:"breaking-changes",level:3},{value:"Improvements",id:"improvements",level:3},{value:"Bug Fixes",id:"bug-fixes",level:3},{value:"Minor Changes",id:"minor-changes",level:3},{value:"7.1.0",id:"710",level:2},{value:"Breaking Changes",id:"breaking-changes-1",level:3},{value:"Improvements",id:"improvements-1",level:3},{value:"7.0.0",id:"700",level:2},{value:"Breaking Changes",id:"breaking-changes-2",level:3},{value:"New Features",id:"new-features",level:3},{value:"Improvements",id:"improvements-2",level:3},{value:"Minor Changes",id:"minor-changes-1",level:3},{value:"6.2.3",id:"623",level:2},{value:"6.2.2",id:"622",level:2},{value:"6.2.1",id:"621",level:2},{value:"6.2.0",id:"620",level:2},{value:"6.1.0",id:"610",level:2},{value:"Breaking Changes",id:"breaking-changes-3",level:3},{value:"Improvements",id:"improvements-3",level:3},{value:"5.0.0",id:"500",level:2},{value:"Dependencies",id:"dependencies",level:3},{value:"4.3.0",id:"430",level:2},{value:"Breaking change",id:"breaking-change",level:3},{value:"Minor changes",id:"minor-changes-2",level:3},{value:"4.2.0",id:"420",level:2},{value:"Breaking change",id:"breaking-change-1",level:3},{value:"New features",id:"new-features-1",level:3},{value:"4.1.0",id:"410",level:2},{value:"Breaking change",id:"breaking-change-2",level:3},{value:"New features",id:"new-features-2",level:3},{value:"Minor changes",id:"minor-changes-3",level:3},{value:"Miscellaneous",id:"miscellaneous",level:3},{value:"4.0.0",id:"400",level:2},{value:"New features",id:"new-features-3",level:3},{value:"Symfony",id:"symfony",level:3},{value:"Laravel",id:"laravel",level:3},{value:"Internals",id:"internals",level:3}],d={toc:s},g="wrapper";function u(e){let{components:a,...n}=e;return(0,i.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"800"},"8.0.0"),(0,i.yg)("h3",{id:"breaking-changes"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/677"},"#677 Drops support for Doctrine annotations")," @fogrye")),(0,i.yg)("h3",{id:"improvements"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/668"},"#668 Adds working examples to docs")," @shish"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/698"},"#698 Performance optimizations and caching in development environments (",(0,i.yg)("inlineCode",{parentName:"a"},"devMode()"),")")," @oprypkhantc]")),(0,i.yg)("h3",{id:"bug-fixes"},"Bug Fixes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/702"},"#702 Fix prefetching for nested fields")," @sudevva")),(0,i.yg)("h3",{id:"minor-changes"},"Minor Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/695"},"#695 Removes dependecy to unmaintained thecodingmachine/cache-utils dependency")," @xyng"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/712"},"#712 Caching improvements with use of multiple ClassFinders")," @andrew-demb")),(0,i.yg)("h2",{id:"710"},"7.1.0"),(0,i.yg)("h3",{id:"breaking-changes-1"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#698 Removes some methods and classes, namely:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Deprecated ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::addControllerNamespace()")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::addTypeNamespace()")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::addNamespace()")),(0,i.yg)("li",{parentName:"ul"},"Deprecated ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setGlobTTL()")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::devMode()")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::prodMode()")),(0,i.yg)("li",{parentName:"ul"},"Removed ",(0,i.yg)("inlineCode",{parentName:"li"},"FactoryContext::get*TTL()")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperFactoryContext::get*TTL()")," as GraphQLite no longer uses TTLs to invalidate caches"),(0,i.yg)("li",{parentName:"ul"},"Removed ",(0,i.yg)("inlineCode",{parentName:"li"},"StaticClassListTypeMapper")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"ClassFinderTypeMapper")," used with ",(0,i.yg)("inlineCode",{parentName:"li"},"StaticClassFinder")),(0,i.yg)("li",{parentName:"ul"},"Renamed ",(0,i.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"ClassFinderTypeMapper")),(0,i.yg)("li",{parentName:"ul"},"Renamed ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setClassBoundCacheContractFactory()")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setClassBoundCache()"),",\n",(0,i.yg)("inlineCode",{parentName:"li"},"FactoryContext::getClassBoundCacheContractFactory()")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"FactoryContext::getClassBoundCache()")," and changed their signatures"),(0,i.yg)("li",{parentName:"ul"},"Removed ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperFactoryContext::getTypeNamespaces()")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperFactoryContext::getClassFinder()"))))),(0,i.yg)("h3",{id:"improvements-1"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#698 Performance optimizations and caching in development environments (",(0,i.yg)("inlineCode",{parentName:"li"},"devMode()"),"). @oprypkhantc")),(0,i.yg)("h2",{id:"700"},"7.0.0"),(0,i.yg)("h3",{id:"breaking-changes-2"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#664 Replaces ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/class-explorer"},"thecodingmachine/class-explorer")," with ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/alekitto/class-finder"},"kcs/class-finder")," resulting in the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setClassNameMapper")," being renamed to ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setFinder"),". This now expects an instance of ",(0,i.yg)("inlineCode",{parentName:"li"},"Kcs\\ClassFinder\\Finder")," instead of ",(0,i.yg)("inlineCode",{parentName:"li"},"Kcs\\ClassFinder\\Finder\\FinderInterface"),". @fogrye")),(0,i.yg)("h3",{id:"new-features"},"New Features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#649 Adds support for ",(0,i.yg)("inlineCode",{parentName:"li"},"subscription")," operations. @oojacoboo"),(0,i.yg)("li",{parentName:"ul"},"#612 Automatic query complexity analysis. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#611 Automatic persisted queries. @oprypkhantc")),(0,i.yg)("h3",{id:"improvements-2"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#658 Improves on prefetching for nested fields. @grynchuk"),(0,i.yg)("li",{parentName:"ul"},"#646 Improves exception handling during schema parsing. @fogrye"),(0,i.yg)("li",{parentName:"ul"},"#636 Allows the use of middleware on construtor params/fields. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#623 Improves support for description arguments on types/fields. @downace"),(0,i.yg)("li",{parentName:"ul"},"#628 Properly handles ",(0,i.yg)("inlineCode",{parentName:"li"},"@param")," annotations for generics support on field annotated constructor arguments. @oojacoboo"),(0,i.yg)("li",{parentName:"ul"},"#584 Immutability improvements across the codebase. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#588 Prefetch improvements. @oprpkhantc"),(0,i.yg)("li",{parentName:"ul"},"#606 Adds support for phpdoc descriptions and deprecation annotations on native enums. @mdoelker"),(0,i.yg)("li",{parentName:"ul"},"Thanks to @shish, @cvergne and @mshapovalov for updating the docs!")),(0,i.yg)("h3",{id:"minor-changes-1"},"Minor Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#639 Added support for Symfony 7. @janatjak")),(0,i.yg)("h2",{id:"623"},"6.2.3"),(0,i.yg)("p",null,"Adds support for ",(0,i.yg)("inlineCode",{parentName:"p"},"Psr\\Container")," 1.1 with #601"),(0,i.yg)("h2",{id:"622"},"6.2.2"),(0,i.yg)("p",null,"This is a very simple release. We support Doctrine annotation 1.x and we've deprecated ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory::setDoctrineAnnotationReader")," in favor of native PHP attributes."),(0,i.yg)("h2",{id:"621"},"6.2.1"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Added support for new ",(0,i.yg)("inlineCode",{parentName:"li"},"Void")," return types, allowing use of ",(0,i.yg)("inlineCode",{parentName:"li"},"void")," from operation resolvers. #574"),(0,i.yg)("li",{parentName:"ul"},"Improvements with authorization middleware #571"),(0,i.yg)("li",{parentName:"ul"},"Updated vendor dependencies: #580 #558")),(0,i.yg)("h2",{id:"620"},"6.2.0"),(0,i.yg)("p",null,"Lots of little nuggets in this release! We're now targeting PHP ^8.1 and have testing on 8.2."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Better support for union types and enums: #530, #535, #561, #570"),(0,i.yg)("li",{parentName:"ul"},"Various bug and interface fixes: #532, #575, #564"),(0,i.yg)("li",{parentName:"ul"},"GraphQL v15 required: #542"),(0,i.yg)("li",{parentName:"ul"},"Lots of codebase improvements, more strict typing: #548")),(0,i.yg)("p",null,"A special thanks to @rusted-love and @oprypkhantc for their contributions."),(0,i.yg)("h2",{id:"610"},"6.1.0"),(0,i.yg)("p",null,"A shoutout to @bladl for his work on this release, improving the code for better typing and PHP 8.0 syntax updates!"),(0,i.yg)("h3",{id:"breaking-changes-3"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#518 PSR-11 support now requires version 2"),(0,i.yg)("li",{parentName:"ul"},"#508 Due to some of the code improvements, additional typing has been added to some interfaces/classes. For instance, ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface::toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface::toGraphQLInputType")," now have the following signatures:")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"}," /**\n * @param (OutputType&GraphQLType)|null $subType\n *\n * @return OutputType&GraphQLType\n */\n public function toGraphQLOutputType(\n Type $type,\n OutputType|null $subType,\n ReflectionMethod|ReflectionProperty $reflector,\n DocBlock $docBlockObj\n ): OutputType;\n\n /**\n * @param (InputType&GraphQLType)|null $subType\n *\n * @return InputType&GraphQLType\n */\n public function toGraphQLInputType(\n Type $type,\n InputType|null $subType,\n string $argumentName,\n ReflectionMethod|ReflectionProperty $reflector,\n DocBlock $docBlockObj\n ): InputType;\n")),(0,i.yg)("h3",{id:"improvements-3"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#510"),(0,i.yg)("li",{parentName:"ul"},"#508")),(0,i.yg)("h2",{id:"500"},"5.0.0"),(0,i.yg)("h3",{id:"dependencies"},"Dependencies"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.yg)("h2",{id:"430"},"4.3.0"),(0,i.yg)("h3",{id:"breaking-change"},"Breaking change"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The method ",(0,i.yg)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.yg)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.yg)("h3",{id:"minor-changes-2"},"Minor changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.yg)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h3",{id:"breaking-change-1"},"Breaking change"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h3",{id:"new-features-1"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Factory]"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Type]")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/input-types#input-attribute"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Logged]"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Right]"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Security]"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h3",{id:"breaking-change-2"},"Breaking change"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h3",{id:"new-features-2"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h3",{id:"minor-changes-3"},"Minor changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h3",{id:"miscellaneous"},"Miscellaneous"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h3",{id:"new-features-3"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"#[Type]")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Assertion]")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Security]")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[InjectUser]")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"#[Decorate]")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("h3",{id:"symfony"},"Symfony"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h3",{id:"laravel"},"Laravel"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h3",{id:"internals"},"Internals"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5170],{52072:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>r,default:()=>u,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var t=n(58168),i=(n(96540),n(15680));n(67443);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"version-8.0.0/changelog",title:"Changelog",description:"8.0.0",source:"@site/versioned_docs/version-8.0.0/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/CHANGELOG.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/semver"}},p={},s=[{value:"8.0.0",id:"800",level:2},{value:"Breaking Changes",id:"breaking-changes",level:3},{value:"Improvements",id:"improvements",level:3},{value:"Bug Fixes",id:"bug-fixes",level:3},{value:"Minor Changes",id:"minor-changes",level:3},{value:"7.1.0",id:"710",level:2},{value:"Breaking Changes",id:"breaking-changes-1",level:3},{value:"Improvements",id:"improvements-1",level:3},{value:"7.0.0",id:"700",level:2},{value:"Breaking Changes",id:"breaking-changes-2",level:3},{value:"New Features",id:"new-features",level:3},{value:"Improvements",id:"improvements-2",level:3},{value:"Minor Changes",id:"minor-changes-1",level:3},{value:"6.2.3",id:"623",level:2},{value:"6.2.2",id:"622",level:2},{value:"6.2.1",id:"621",level:2},{value:"6.2.0",id:"620",level:2},{value:"6.1.0",id:"610",level:2},{value:"Breaking Changes",id:"breaking-changes-3",level:3},{value:"Improvements",id:"improvements-3",level:3},{value:"5.0.0",id:"500",level:2},{value:"Dependencies",id:"dependencies",level:3},{value:"4.3.0",id:"430",level:2},{value:"Breaking change",id:"breaking-change",level:3},{value:"Minor changes",id:"minor-changes-2",level:3},{value:"4.2.0",id:"420",level:2},{value:"Breaking change",id:"breaking-change-1",level:3},{value:"New features",id:"new-features-1",level:3},{value:"4.1.0",id:"410",level:2},{value:"Breaking change",id:"breaking-change-2",level:3},{value:"New features",id:"new-features-2",level:3},{value:"Minor changes",id:"minor-changes-3",level:3},{value:"Miscellaneous",id:"miscellaneous",level:3},{value:"4.0.0",id:"400",level:2},{value:"New features",id:"new-features-3",level:3},{value:"Symfony",id:"symfony",level:3},{value:"Laravel",id:"laravel",level:3},{value:"Internals",id:"internals",level:3}],d={toc:s},g="wrapper";function u(e){let{components:a,...n}=e;return(0,i.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"800"},"8.0.0"),(0,i.yg)("h3",{id:"breaking-changes"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/677"},"#677 Drops support for Doctrine annotations")," @fogrye")),(0,i.yg)("h3",{id:"improvements"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/668"},"#668 Adds working examples to docs")," @shish"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/698"},"#698 Performance optimizations and caching in development environments (",(0,i.yg)("inlineCode",{parentName:"a"},"devMode()"),")")," @oprypkhantc]")),(0,i.yg)("h3",{id:"bug-fixes"},"Bug Fixes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/702"},"#702 Fix prefetching for nested fields")," @sudevva")),(0,i.yg)("h3",{id:"minor-changes"},"Minor Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/695"},"#695 Removes dependecy to unmaintained thecodingmachine/cache-utils dependency")," @xyng"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/712"},"#712 Caching improvements with use of multiple ClassFinders")," @andrew-demb")),(0,i.yg)("h2",{id:"710"},"7.1.0"),(0,i.yg)("h3",{id:"breaking-changes-1"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#698 Removes some methods and classes, namely:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Deprecated ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::addControllerNamespace()")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::addTypeNamespace()")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::addNamespace()")),(0,i.yg)("li",{parentName:"ul"},"Deprecated ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setGlobTTL()")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::devMode()")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::prodMode()")),(0,i.yg)("li",{parentName:"ul"},"Removed ",(0,i.yg)("inlineCode",{parentName:"li"},"FactoryContext::get*TTL()")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperFactoryContext::get*TTL()")," as GraphQLite no longer uses TTLs to invalidate caches"),(0,i.yg)("li",{parentName:"ul"},"Removed ",(0,i.yg)("inlineCode",{parentName:"li"},"StaticClassListTypeMapper")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"ClassFinderTypeMapper")," used with ",(0,i.yg)("inlineCode",{parentName:"li"},"StaticClassFinder")),(0,i.yg)("li",{parentName:"ul"},"Renamed ",(0,i.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"ClassFinderTypeMapper")),(0,i.yg)("li",{parentName:"ul"},"Renamed ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setClassBoundCacheContractFactory()")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setClassBoundCache()"),",\n",(0,i.yg)("inlineCode",{parentName:"li"},"FactoryContext::getClassBoundCacheContractFactory()")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"FactoryContext::getClassBoundCache()")," and changed their signatures"),(0,i.yg)("li",{parentName:"ul"},"Removed ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperFactoryContext::getTypeNamespaces()")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperFactoryContext::getClassFinder()"))))),(0,i.yg)("h3",{id:"improvements-1"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#698 Performance optimizations and caching in development environments (",(0,i.yg)("inlineCode",{parentName:"li"},"devMode()"),"). @oprypkhantc")),(0,i.yg)("h2",{id:"700"},"7.0.0"),(0,i.yg)("h3",{id:"breaking-changes-2"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#664 Replaces ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/class-explorer"},"thecodingmachine/class-explorer")," with ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/alekitto/class-finder"},"kcs/class-finder")," resulting in the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setClassNameMapper")," being renamed to ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setFinder"),". This now expects an instance of ",(0,i.yg)("inlineCode",{parentName:"li"},"Kcs\\ClassFinder\\Finder")," instead of ",(0,i.yg)("inlineCode",{parentName:"li"},"Kcs\\ClassFinder\\Finder\\FinderInterface"),". @fogrye")),(0,i.yg)("h3",{id:"new-features"},"New Features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#649 Adds support for ",(0,i.yg)("inlineCode",{parentName:"li"},"subscription")," operations. @oojacoboo"),(0,i.yg)("li",{parentName:"ul"},"#612 Automatic query complexity analysis. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#611 Automatic persisted queries. @oprypkhantc")),(0,i.yg)("h3",{id:"improvements-2"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#658 Improves on prefetching for nested fields. @grynchuk"),(0,i.yg)("li",{parentName:"ul"},"#646 Improves exception handling during schema parsing. @fogrye"),(0,i.yg)("li",{parentName:"ul"},"#636 Allows the use of middleware on construtor params/fields. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#623 Improves support for description arguments on types/fields. @downace"),(0,i.yg)("li",{parentName:"ul"},"#628 Properly handles ",(0,i.yg)("inlineCode",{parentName:"li"},"@param")," annotations for generics support on field annotated constructor arguments. @oojacoboo"),(0,i.yg)("li",{parentName:"ul"},"#584 Immutability improvements across the codebase. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#588 Prefetch improvements. @oprpkhantc"),(0,i.yg)("li",{parentName:"ul"},"#606 Adds support for phpdoc descriptions and deprecation annotations on native enums. @mdoelker"),(0,i.yg)("li",{parentName:"ul"},"Thanks to @shish, @cvergne and @mshapovalov for updating the docs!")),(0,i.yg)("h3",{id:"minor-changes-1"},"Minor Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#639 Added support for Symfony 7. @janatjak")),(0,i.yg)("h2",{id:"623"},"6.2.3"),(0,i.yg)("p",null,"Adds support for ",(0,i.yg)("inlineCode",{parentName:"p"},"Psr\\Container")," 1.1 with #601"),(0,i.yg)("h2",{id:"622"},"6.2.2"),(0,i.yg)("p",null,"This is a very simple release. We support Doctrine annotation 1.x and we've deprecated ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory::setDoctrineAnnotationReader")," in favor of native PHP attributes."),(0,i.yg)("h2",{id:"621"},"6.2.1"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Added support for new ",(0,i.yg)("inlineCode",{parentName:"li"},"Void")," return types, allowing use of ",(0,i.yg)("inlineCode",{parentName:"li"},"void")," from operation resolvers. #574"),(0,i.yg)("li",{parentName:"ul"},"Improvements with authorization middleware #571"),(0,i.yg)("li",{parentName:"ul"},"Updated vendor dependencies: #580 #558")),(0,i.yg)("h2",{id:"620"},"6.2.0"),(0,i.yg)("p",null,"Lots of little nuggets in this release! We're now targeting PHP ^8.1 and have testing on 8.2."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Better support for union types and enums: #530, #535, #561, #570"),(0,i.yg)("li",{parentName:"ul"},"Various bug and interface fixes: #532, #575, #564"),(0,i.yg)("li",{parentName:"ul"},"GraphQL v15 required: #542"),(0,i.yg)("li",{parentName:"ul"},"Lots of codebase improvements, more strict typing: #548")),(0,i.yg)("p",null,"A special thanks to @rusted-love and @oprypkhantc for their contributions."),(0,i.yg)("h2",{id:"610"},"6.1.0"),(0,i.yg)("p",null,"A shoutout to @bladl for his work on this release, improving the code for better typing and PHP 8.0 syntax updates!"),(0,i.yg)("h3",{id:"breaking-changes-3"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#518 PSR-11 support now requires version 2"),(0,i.yg)("li",{parentName:"ul"},"#508 Due to some of the code improvements, additional typing has been added to some interfaces/classes. For instance, ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface::toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface::toGraphQLInputType")," now have the following signatures:")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"}," /**\n * @param (OutputType&GraphQLType)|null $subType\n *\n * @return OutputType&GraphQLType\n */\n public function toGraphQLOutputType(\n Type $type,\n OutputType|null $subType,\n ReflectionMethod|ReflectionProperty $reflector,\n DocBlock $docBlockObj\n ): OutputType;\n\n /**\n * @param (InputType&GraphQLType)|null $subType\n *\n * @return InputType&GraphQLType\n */\n public function toGraphQLInputType(\n Type $type,\n InputType|null $subType,\n string $argumentName,\n ReflectionMethod|ReflectionProperty $reflector,\n DocBlock $docBlockObj\n ): InputType;\n")),(0,i.yg)("h3",{id:"improvements-3"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#510"),(0,i.yg)("li",{parentName:"ul"},"#508")),(0,i.yg)("h2",{id:"500"},"5.0.0"),(0,i.yg)("h3",{id:"dependencies"},"Dependencies"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.yg)("h2",{id:"430"},"4.3.0"),(0,i.yg)("h3",{id:"breaking-change"},"Breaking change"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The method ",(0,i.yg)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.yg)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.yg)("h3",{id:"minor-changes-2"},"Minor changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.yg)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h3",{id:"breaking-change-1"},"Breaking change"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h3",{id:"new-features-1"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Factory]"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Type]")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/input-types#input-attribute"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Logged]"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Right]"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Security]"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h3",{id:"breaking-change-2"},"Breaking change"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h3",{id:"new-features-2"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h3",{id:"minor-changes-3"},"Minor changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h3",{id:"miscellaneous"},"Miscellaneous"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h3",{id:"new-features-3"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"#[Type]")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Assertion]")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Security]")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[InjectUser]")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"#[Decorate]")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("h3",{id:"symfony"},"Symfony"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h3",{id:"laravel"},"Laravel"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h3",{id:"internals"},"Internals"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6cfcfcfb.b23423d9.js b/assets/js/6cfcfcfb.0dd10615.js similarity index 99% rename from assets/js/6cfcfcfb.b23423d9.js rename to assets/js/6cfcfcfb.0dd10615.js index 6c4177580..931876933 100644 --- a/assets/js/6cfcfcfb.b23423d9.js +++ b/assets/js/6cfcfcfb.0dd10615.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8798],{77660:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>r,default:()=>y,frontMatter:()=>i,metadata:()=>l,toc:()=>s});var t=a(58168),p=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function y(e){let{components:n,...a}=e;return(0,p.yg)(g,(0,t.A)({},u,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/3.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/3.0/custom-output-types"},"custom output types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"You can create a GraphQL union type ",(0,p.yg)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.yg)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.yg)("pre",null,(0,p.yg)("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")))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8798],{77660:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>r,default:()=>y,frontMatter:()=>i,metadata:()=>l,toc:()=>s});var t=a(58168),p=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function y(e){let{components:n,...a}=e;return(0,p.yg)(g,(0,t.A)({},u,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/3.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/3.0/custom-output-types"},"custom output types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"You can create a GraphQL union type ",(0,p.yg)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.yg)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.yg)("pre",null,(0,p.yg)("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")))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6d89025c.6b2e999b.js b/assets/js/6d89025c.8c59f230.js similarity index 99% rename from assets/js/6d89025c.6b2e999b.js rename to assets/js/6d89025c.8c59f230.js index 1cce9bd93..24da549d7 100644 --- a/assets/js/6d89025c.6b2e999b.js +++ b/assets/js/6d89025c.8c59f230.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1190],{19365:(e,n,t)=>{t.d(n,{A:()=>u});var a=t(96540),l=t(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:n,hidden:t,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),l=t(96540),r=t(20053),u=t(23104),o=t(56347),i=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.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:l}}=e;return{value:n,label:t,attributes:a,default:l}}))}function d(e){const{values:n,children:t}=e;return(0,l.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 m(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,o.W6)(),r=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.aZ)(r),(0,l.useCallback)((e=>{if(!r)return;const n=new URLSearchParams(a.location.search);n.set(r,e),a.replace({...a.location,search:n.toString()})}),[r,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.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(!m({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:r}))),[i,s]=g({queryString:t,groupId:a}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,r]=(0,c.Dv)(t);return[a,(0,l.useCallback)((e=>{t&&r.set(e)}),[t,r])]}({groupId:a}),h=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);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),y(e)}),[s,y,r]),tabValues:r}}var h=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==o&&(p(n),i(a))},m=e=>{let n=null;switch(e.key){case"Enter":d(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 l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:u}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const r=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,l.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function q(e){const n=y(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,n)),l.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(n)},e))}},62141:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=t(58168),l=(t(96540),t(15680)),r=(t(67443),t(11470)),u=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,l.yg)(m,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("div",{class:"alert alert--warning"},(0,l.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.yg)("p",null,"By settings ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.yg)("p",null,"The mutation below will log-in a user:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.yg)("p",null,"In Symfony, user objects implement ",(0,l.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.yg)("p",null,"If you want to get more fields, just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"You can now query this field using an ",(0,l.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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")))))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1190],{19365:(e,n,t)=>{t.d(n,{A:()=>u});var a=t(96540),l=t(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:n,hidden:t,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),l=t(96540),r=t(20053),u=t(23104),o=t(56347),i=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.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:l}}=e;return{value:n,label:t,attributes:a,default:l}}))}function d(e){const{values:n,children:t}=e;return(0,l.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 m(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,o.W6)(),r=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.aZ)(r),(0,l.useCallback)((e=>{if(!r)return;const n=new URLSearchParams(a.location.search);n.set(r,e),a.replace({...a.location,search:n.toString()})}),[r,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.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(!m({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:r}))),[i,s]=g({queryString:t,groupId:a}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,r]=(0,c.Dv)(t);return[a,(0,l.useCallback)((e=>{t&&r.set(e)}),[t,r])]}({groupId:a}),h=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);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),y(e)}),[s,y,r]),tabValues:r}}var h=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==o&&(p(n),i(a))},m=e=>{let n=null;switch(e.key){case"Enter":d(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 l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:u}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const r=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,l.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function q(e){const n=y(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,n)),l.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(n)},e))}},62141:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=t(58168),l=(t(96540),t(15680)),r=(t(67443),t(11470)),u=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,l.yg)(m,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("div",{class:"alert alert--warning"},(0,l.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.yg)("p",null,"By settings ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.yg)("p",null,"The mutation below will log-in a user:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.yg)("p",null,"In Symfony, user objects implement ",(0,l.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.yg)("p",null,"If you want to get more fields, just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"You can now query this field using an ",(0,l.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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")))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6efd6ec9.5d3e0f7f.js b/assets/js/6efd6ec9.45f89857.js similarity index 99% rename from assets/js/6efd6ec9.5d3e0f7f.js rename to assets/js/6efd6ec9.45f89857.js index f4f7cb562..0e17ca281 100644 --- a/assets/js/6efd6ec9.5d3e0f7f.js +++ b/assets/js/6efd6ec9.45f89857.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4805],{96421:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>l,contentTitle:()=>r,default:()=>m,frontMatter:()=>i,metadata:()=>s,toc:()=>o});var t=a(58168),p=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function m(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},u,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.0/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"You can create a GraphQL union type ",(0,p.yg)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.yg)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.yg)("p",null,"You will first need to install ",(0,p.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("em",null,"type mappers")," in the ",(0,p.yg)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4805],{96421:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>l,contentTitle:()=>r,default:()=>m,frontMatter:()=>i,metadata:()=>s,toc:()=>o});var t=a(58168),p=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function m(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},u,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.0/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.0/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"You can create a GraphQL union type ",(0,p.yg)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.yg)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.yg)("p",null,"You will first need to install ",(0,p.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("em",null,"type mappers")," in the ",(0,p.yg)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("a",{parentName:"p",href:"custom-types#registering-a-custom-scalar-type-advanced"},"you can develop your own scalar types"),"."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6fe30f11.e39ea11f.js b/assets/js/6fe30f11.5db9e4f0.js similarity index 99% rename from assets/js/6fe30f11.e39ea11f.js rename to assets/js/6fe30f11.5db9e4f0.js index dd6e3ff91..678b5cab1 100644 --- a/assets/js/6fe30f11.e39ea11f.js +++ b/assets/js/6fe30f11.5db9e4f0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5235],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(s.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),s=n(20053),o=n(23104),l=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("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 T(e){const t=f(e);return r.createElement("div",{className:(0,s.A)("tabs-container",y.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,b.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},90488:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),s=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/3.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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([[5235],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(s.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),s=n(20053),o=n(23104),l=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("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 T(e){const t=f(e);return r.createElement("div",{className:(0,s.A)("tabs-container",y.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,b.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},90488:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),s=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/3.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.55388635.js b/assets/js/71a56230.13b5bfe0.js similarity index 97% rename from assets/js/71a56230.55388635.js rename to assets/js/71a56230.13b5bfe0.js index a1633c872..1b9ef9870 100644 --- a/assets/js/71a56230.55388635.js +++ b/assets/js/71a56230.13b5bfe0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3332],{11277:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>p,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],g={toc:u},c="wrapper";function p(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},g,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3332],{11277:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>p,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],g={toc:u},c="wrapper";function p(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},g,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/72be5fd7.c66c8d29.js b/assets/js/72be5fd7.546b0d97.js similarity index 99% rename from assets/js/72be5fd7.c66c8d29.js rename to assets/js/72be5fd7.546b0d97.js index 08cd4b52e..1fe15608c 100644 --- a/assets/js/72be5fd7.c66c8d29.js +++ b/assets/js/72be5fd7.546b0d97.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7045],{19365:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(96540),r=a(20053);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.A)(l.tabItem,i),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>x});var n=a(58168),r=a(96540),l=a(20053),i=a(23104),o=a(56347),u=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(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(!y({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,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return y({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),h(e)}),[s,h,l]),tabValues:l}}var f=a(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},y=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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:y,onClick:d},i,{className:(0,l.A)("tabs__item",g.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 T(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",g.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function x(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},42209:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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-7.0.0/extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-7.0.0/extend-input-type.mdx",sourceDirName:".",slug:"/extend-input-type",permalink:"/docs/7.0.0/extend-input-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/extend-input-type.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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/7.0.0/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/7.0.0/multiple-output-types"}},p={},c=[],d={toc:c},y="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/extend-type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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([[7045],{19365:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(96540),r=a(20053);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.A)(l.tabItem,i),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>x});var n=a(58168),r=a(96540),l=a(20053),i=a(23104),o=a(56347),u=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(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(!y({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,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return y({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),h(e)}),[s,h,l]),tabValues:l}}var f=a(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},y=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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:y,onClick:d},i,{className:(0,l.A)("tabs__item",g.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 T(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",g.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function x(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},42209:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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-7.0.0/extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-7.0.0/extend-input-type.mdx",sourceDirName:".",slug:"/extend-input-type",permalink:"/docs/7.0.0/extend-input-type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/extend-input-type.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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/7.0.0/argument-resolving"},next:{title:"Class with multiple output types",permalink:"/docs/7.0.0/multiple-output-types"}},p={},c=[],d={toc:c},y="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/extend-type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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/72d0dc3a.fd9375e2.js b/assets/js/72d0dc3a.f74b51d2.js similarity index 97% rename from assets/js/72d0dc3a.fd9375e2.js rename to assets/js/72d0dc3a.f74b51d2.js index c111f0c2b..040dc5bfb 100644 --- a/assets/js/72d0dc3a.fd9375e2.js +++ b/assets/js/72d0dc3a.f74b51d2.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7035],{50983:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7035],{50983:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/73ccb1b9.90069866.js b/assets/js/73ccb1b9.530685ad.js similarity index 99% rename from assets/js/73ccb1b9.90069866.js rename to assets/js/73ccb1b9.530685ad.js index 890d7fa09..caf2e4a41 100644 --- a/assets/js/73ccb1b9.90069866.js +++ b/assets/js/73ccb1b9.530685ad.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5083],{12894:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"version-8.0.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-8.0.0/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-8.0.0/laravel-package.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function u(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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([[5083],{12894:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);const l={id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},o=void 0,i={unversionedId:"laravel-package",id:"version-8.0.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-8.0.0/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-8.0.0/laravel-package.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function u(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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/741df2ae.a683b422.js b/assets/js/741df2ae.936ca227.js similarity index 99% rename from assets/js/741df2ae.a683b422.js rename to assets/js/741df2ae.936ca227.js index e8bb43ae7..a6bc8b51c 100644 --- a/assets/js/741df2ae.a683b422.js +++ b/assets/js/741df2ae.936ca227.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6095],{88948:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>o,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Type]")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"#[ExtendType]")," attribute and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/next/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6095],{88948:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>o,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>l,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Type]")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"#[ExtendType]")," attribute and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/next/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/74383bd8.9ddbd2d1.js b/assets/js/74383bd8.fc1132ac.js similarity index 99% rename from assets/js/74383bd8.9ddbd2d1.js rename to assets/js/74383bd8.fc1132ac.js index ca4064829..611f512bb 100644 --- a/assets/js/74383bd8.9ddbd2d1.js +++ b/assets/js/74383bd8.fc1132ac.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4884],{93047:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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/6.1/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/internals.md",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"docs",previous:{title:"Laravel specific features",permalink:"/docs/6.1/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/6.1/troubleshooting"}},l={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/6.1/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.1/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4884],{93047:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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/6.1/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/internals.md",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"docs",previous:{title:"Laravel specific features",permalink:"/docs/6.1/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/6.1/troubleshooting"}},l={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/6.1/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.1/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7515d7ec.4b2d0413.js b/assets/js/7515d7ec.32145f60.js similarity index 99% rename from assets/js/7515d7ec.4b2d0413.js rename to assets/js/7515d7ec.32145f60.js index 8b229eeeb..4b3e28402 100644 --- a/assets/js/7515d7ec.4b2d0413.js +++ b/assets/js/7515d7ec.32145f60.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9870],{19365:(e,a,t)=>{t.d(a,{A:()=>o});var n=t(96540),r=t(20053);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:a,hidden:t,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,o),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),l=t(20053),o=t(23104),s=t(56347),i=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function g(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function d(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,s.W6)(),l=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,i.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(n.location.search);a.set(l,e),n.replace({...n.location,search:a.toString()})}),[l,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,l=g(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!d({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:l}))),[i,u]=y({queryString:t,groupId:n}),[c,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,l]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:n}),m=(()=>{const e=i??c;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&s(m)}),[m]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),h(e)}),[u,h,l]),tabValues:l}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:a,block:t,selectedValue:s,selectValue:i,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),g=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==s&&(c(a),i(n))},d=e=>{let a=null;switch(e.key){case"Enter":g(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:s===a?0:-1,"aria-selected":s===a,key:a,ref:e=>p.push(e),onKeyDown:d,onClick:g},o,{className:(0,l.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":s===a})}),t??a)})))}function v(e){let{lazy:a,children:t,selectedValue:n}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function N(e){const a=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,a)),r.createElement(v,(0,n.A)({},e,a)))}function T(e){const a=(0,m.A)();return r.createElement(N,(0,n.A)({key:String(a)},e))}},34991:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>i,default:()=>y,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:c},d="wrapper";function y(e){let{components:a,...t}=e;return(0,r.yg)(d,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"If the ",(0,r.yg)("a",{parentName:"p",href:"/docs/3.0/authentication_authorization#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.yg)("li",{parentName:"ul"},"...")),(0,r.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.yg)("code",null,"@Security")," annotation and Symfony's ",(0,r.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.yg)("h2",{id:"the-is_granted-function"},"The ",(0,r.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.yg)("p",null,"is similar to"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.yg)("p",null,"In addition, the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"PHP 7")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.yg)("a",{parentName:"p",href:"/docs/3.0/authentication_authorization#not-throwing-errors"},(0,r.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"You cannot use the ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.yg)("p",null,"If you are using Laravel, you will ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.yg)("p",null,"If you are using another framework, you need to know that the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.yg)("a",{parentName:"p",href:"/docs/3.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9870],{19365:(e,a,t)=>{t.d(a,{A:()=>o});var n=t(96540),r=t(20053);const l={tabItem:"tabItem_Ymn6"};function o(e){let{children:a,hidden:t,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,o),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),l=t(20053),o=t(23104),s=t(56347),i=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function g(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function d(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,s.W6)(),l=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,i.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(n.location.search);a.set(l,e),n.replace({...n.location,search:a.toString()})}),[l,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,l=g(e),[o,s]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!d({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:l}))),[i,u]=y({queryString:t,groupId:n}),[c,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,l]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:n}),m=(()=>{const e=i??c;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&s(m)}),[m]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),h(e)}),[u,h,l]),tabValues:l}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:a,block:t,selectedValue:s,selectValue:i,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),g=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==s&&(c(a),i(n))},d=e=>{let a=null;switch(e.key){case"Enter":g(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:s===a?0:-1,"aria-selected":s===a,key:a,ref:e=>p.push(e),onKeyDown:d,onClick:g},o,{className:(0,l.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":s===a})}),t??a)})))}function v(e){let{lazy:a,children:t,selectedValue:n}=e;const l=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function N(e){const a=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,a)),r.createElement(v,(0,n.A)({},e,a)))}function T(e){const a=(0,m.A)();return r.createElement(N,(0,n.A)({key:String(a)},e))}},34991:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>i,default:()=>y,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:c},d="wrapper";function y(e){let{components:a,...t}=e;return(0,r.yg)(d,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"If the ",(0,r.yg)("a",{parentName:"p",href:"/docs/3.0/authentication_authorization#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.yg)("li",{parentName:"ul"},"...")),(0,r.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.yg)("code",null,"@Security")," annotation and Symfony's ",(0,r.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.yg)("h2",{id:"the-is_granted-function"},"The ",(0,r.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.yg)("p",null,"is similar to"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.yg)("p",null,"In addition, the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"PHP 7")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.yg)("a",{parentName:"p",href:"/docs/3.0/authentication_authorization#not-throwing-errors"},(0,r.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"You cannot use the ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.yg)("p",null,"If you are using Laravel, you will ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.yg)("p",null,"If you are using another framework, you need to know that the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.yg)("a",{parentName:"p",href:"/docs/3.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/756c6ac7.11f1af27.js b/assets/js/756c6ac7.453122bd.js similarity index 99% rename from assets/js/756c6ac7.11f1af27.js rename to assets/js/756c6ac7.453122bd.js index fe89802a1..bbce37ade 100644 --- a/assets/js/756c6ac7.11f1af27.js +++ b/assets/js/756c6ac7.453122bd.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3419],{19365:(e,n,t)=>{t.d(n,{A:()=>u});var a=t(96540),l=t(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:n,hidden:t,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),l=t(96540),r=t(20053),u=t(23104),o=t(56347),i=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.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:l}}=e;return{value:n,label:t,attributes:a,default:l}}))}function d(e){const{values:n,children:t}=e;return(0,l.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 m(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,o.W6)(),r=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.aZ)(r),(0,l.useCallback)((e=>{if(!r)return;const n=new URLSearchParams(a.location.search);n.set(r,e),a.replace({...a.location,search:n.toString()})}),[r,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.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(!m({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:r}))),[i,s]=g({queryString:t,groupId:a}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,r]=(0,c.Dv)(t);return[a,(0,l.useCallback)((e=>{t&&r.set(e)}),[t,r])]}({groupId:a}),h=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);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),y(e)}),[s,y,r]),tabValues:r}}var h=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==o&&(p(n),i(a))},m=e=>{let n=null;switch(e.key){case"Enter":d(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 l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:u}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const r=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,l.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function q(e){const n=y(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,n)),l.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(n)},e))}},30768:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=t(58168),l=(t(96540),t(15680)),r=(t(67443),t(11470)),u=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,l.yg)(m,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("div",{class:"alert alert--warning"},(0,l.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.yg)("p",null,"By settings ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.yg)("p",null,"The mutation below will log-in a user:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.yg)("p",null,"In Symfony, user objects implement ",(0,l.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.yg)("p",null,"If you want to get more fields, just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"You can now query this field using an ",(0,l.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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")))))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3419],{19365:(e,n,t)=>{t.d(n,{A:()=>u});var a=t(96540),l=t(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:n,hidden:t,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),l=t(96540),r=t(20053),u=t(23104),o=t(56347),i=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.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:l}}=e;return{value:n,label:t,attributes:a,default:l}}))}function d(e){const{values:n,children:t}=e;return(0,l.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 m(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,o.W6)(),r=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.aZ)(r),(0,l.useCallback)((e=>{if(!r)return;const n=new URLSearchParams(a.location.search);n.set(r,e),a.replace({...a.location,search:n.toString()})}),[r,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.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(!m({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:r}))),[i,s]=g({queryString:t,groupId:a}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,r]=(0,c.Dv)(t);return[a,(0,l.useCallback)((e=>{t&&r.set(e)}),[t,r])]}({groupId:a}),h=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);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),y(e)}),[s,y,r]),tabValues:r}}var h=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==o&&(p(n),i(a))},m=e=>{let n=null;switch(e.key){case"Enter":d(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 l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:u}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const r=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,l.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function q(e){const n=y(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,n)),l.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(n)},e))}},30768:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=t(58168),l=(t(96540),t(15680)),r=(t(67443),t(11470)),u=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,l.yg)(m,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("div",{class:"alert alert--warning"},(0,l.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.yg)("p",null,"By settings ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.yg)("p",null,"The mutation below will log-in a user:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.yg)("p",null,"In Symfony, user objects implement ",(0,l.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.yg)("p",null,"If you want to get more fields, just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"You can now query this field using an ",(0,l.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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")))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/75cc8326.b16c1c96.js b/assets/js/75cc8326.f04a2c05.js similarity index 99% rename from assets/js/75cc8326.b16c1c96.js rename to assets/js/75cc8326.f04a2c05.js index 7f18b2b70..ee6b40489 100644 --- a/assets/js/75cc8326.b16c1c96.js +++ b/assets/js/75cc8326.f04a2c05.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8718],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),u=a(56347),i=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),g=(()=>{const e=i??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&u(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}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var g=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},94780:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(m,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.yg)("p",null,"You must start by installing this package:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.yg)("h2",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.yg)("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.yg)("h2",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.yg)("p",null,"In order to use this, you must first be sure that the ",(0,r.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.yg)("pre",null,(0,r.yg)("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([[8718],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),u=a(56347),i=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),g=(()=>{const e=i??d;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&u(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}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var g=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},94780:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(m,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.yg)("p",null,"You must start by installing this package:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.yg)("h2",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.yg)("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.yg)("h2",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.yg)("p",null,"In order to use this, you must first be sure that the ",(0,r.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.yg)("pre",null,(0,r.yg)("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.572d4fd6.js b/assets/js/766e1cc8.77a3fb64.js similarity index 99% rename from assets/js/766e1cc8.572d4fd6.js rename to assets/js/766e1cc8.77a3fb64.js index 23eac9f04..5576f8786 100644 --- a/assets/js/766e1cc8.572d4fd6.js +++ b/assets/js/766e1cc8.77a3fb64.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7362],{42528:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>r,default:()=>y,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var a=n(58168),o=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 y(e){let{components:t,...n}=e;return(0,o.yg)(c,(0,a.A)({},s,n,{components:t,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"Let's admit you are developing an API that returns a list of cities around a location."),(0,o.yg)("p",null,"Your GraphQL query might look like this:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,o.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,o.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,o.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,o.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,o.yg)("p",null,"In order to declare that type, in GraphQLite, we will declare a ",(0,o.yg)("strong",{parentName:"p"},"Factory"),"."),(0,o.yg)("p",null,"A ",(0,o.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,o.yg)("p",null,"Here is an example of factory:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,o.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,o.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,o.yg)("p",null,"A few important things to notice:"),(0,o.yg)("ul",null,(0,o.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,o.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,o.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,o.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')),(0,o.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,o.yg)("p",null,"You can use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,o.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,o.yg)("small",null,"Available in GraphQLite 4.0+"),(0,o.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,o.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,o.yg)("p",null,"Here is an annotated sample:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,o.yg)("small",null,"Available in GraphQLite 4.0+"),(0,o.yg)("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.yg)("p",null,"Image your ",(0,o.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,o.yg)("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.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"With the ",(0,o.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,o.yg)("p",null,"To be able to hide an argument, the argument must have a default value."))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7362],{42528:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>r,default:()=>y,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var a=n(58168),o=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 y(e){let{components:t,...n}=e;return(0,o.yg)(c,(0,a.A)({},s,n,{components:t,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"Let's admit you are developing an API that returns a list of cities around a location."),(0,o.yg)("p",null,"Your GraphQL query might look like this:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,o.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,o.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,o.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,o.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,o.yg)("p",null,"In order to declare that type, in GraphQLite, we will declare a ",(0,o.yg)("strong",{parentName:"p"},"Factory"),"."),(0,o.yg)("p",null,"A ",(0,o.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,o.yg)("p",null,"Here is an example of factory:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,o.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,o.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,o.yg)("p",null,"A few important things to notice:"),(0,o.yg)("ul",null,(0,o.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,o.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,o.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,o.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')),(0,o.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,o.yg)("p",null,"You can use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,o.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,o.yg)("small",null,"Available in GraphQLite 4.0+"),(0,o.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,o.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,o.yg)("p",null,"Here is an annotated sample:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,o.yg)("small",null,"Available in GraphQLite 4.0+"),(0,o.yg)("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.yg)("p",null,"Image your ",(0,o.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,o.yg)("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.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"With the ",(0,o.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,o.yg)("p",null,"To be able to hide an argument, the argument must have a default value."))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/767c28af.f76bd5cf.js b/assets/js/767c28af.d9ac76d3.js similarity index 99% rename from assets/js/767c28af.f76bd5cf.js rename to assets/js/767c28af.d9ac76d3.js index 5c33c706b..a57ea486a 100644 --- a/assets/js/767c28af.f76bd5cf.js +++ b/assets/js/767c28af.d9ac76d3.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[229],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var r=a(96540),n=a(20053);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.A)(l.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var r=a(58168),n=a(96540),l=a(20053),u=a(23104),o=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{queryString:t=!1,groupId:a}=e;const r=(0,o.W6)(),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.aZ)(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 h(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]=g({queryString:a,groupId:r}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[r,l]=(0,c.Dv)(a);return[r,(0,n.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:r}),b=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,n.useLayoutEffect)((()=>{b&&o(b)}),[b]);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),h(e)}),[i,h,l]),tabValues:l}}var b=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return n.createElement("li",(0,r.A)({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.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(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 w(e){const t=h(e);return n.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},n.createElement(y,(0,r.A)({},e,t)),n.createElement(v,(0,r.A)({},e,t)))}function T(e){const t=(0,b.A)();return n.createElement(w,(0,r.A)({key:String(t)},e))}},24432:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var r=a(58168),n=(a(96540),a(15680)),l=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:t,...a}=e;return(0,n.yg)(m,(0,r.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,n.yg)("p",{align:"center"},(0,n.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,n.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,n.yg)("h2",{id:"features"},"Features"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,n.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,n.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,n.yg)("h2",{id:"basic-example"},"Basic example"),(0,n.yg)("p",null,"First, declare a query in your controller:"),(0,n.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,n.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,n.yg)("pre",null,(0,n.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,n.yg)("pre",null,(0,n.yg)("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.yg)("p",null,"Then, annotate the ",(0,n.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,n.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,n.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,n.yg)("pre",null,(0,n.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,n.yg)("pre",null,(0,n.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,n.yg)("pre",null,(0,n.yg)("code",{parentName:"pre",className:"language-grapql"},"{\n product(id: 42) {\n name\n }\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[229],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var r=a(96540),n=a(20053);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.A)(l.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var r=a(58168),n=a(96540),l=a(20053),u=a(23104),o=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{queryString:t=!1,groupId:a}=e;const r=(0,o.W6)(),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.aZ)(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 h(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]=g({queryString:a,groupId:r}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[r,l]=(0,c.Dv)(a);return[r,(0,n.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:r}),b=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,n.useLayoutEffect)((()=>{b&&o(b)}),[b]);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),h(e)}),[i,h,l]),tabValues:l}}var b=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return n.createElement("li",(0,r.A)({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.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===t})}),a??t)})))}function v(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 w(e){const t=h(e);return n.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},n.createElement(y,(0,r.A)({},e,t)),n.createElement(v,(0,r.A)({},e,t)))}function T(e){const t=(0,b.A)();return n.createElement(w,(0,r.A)({key:String(t)},e))}},24432:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var r=a(58168),n=(a(96540),a(15680)),l=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:t,...a}=e;return(0,n.yg)(m,(0,r.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,n.yg)("p",{align:"center"},(0,n.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,n.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,n.yg)("h2",{id:"features"},"Features"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,n.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,n.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,n.yg)("h2",{id:"basic-example"},"Basic example"),(0,n.yg)("p",null,"First, declare a query in your controller:"),(0,n.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,n.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,n.yg)("pre",null,(0,n.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,n.yg)("pre",null,(0,n.yg)("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.yg)("p",null,"Then, annotate the ",(0,n.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,n.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,n.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,n.yg)("pre",null,(0,n.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,n.yg)("pre",null,(0,n.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,n.yg)("pre",null,(0,n.yg)("code",{parentName:"pre",className:"language-grapql"},"{\n product(id: 42) {\n name\n }\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/77cdcd82.1c973b5a.js b/assets/js/77cdcd82.c070a849.js similarity index 97% rename from assets/js/77cdcd82.1c973b5a.js rename to assets/js/77cdcd82.c070a849.js index cc0b1b724..0981e8db2 100644 --- a/assets/js/77cdcd82.1c973b5a.js +++ b/assets/js/77cdcd82.c070a849.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3507],{56855:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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/6.1/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/troubleshooting.md",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/6.1/internals"},next:{title:"Migrating",permalink:"/docs/6.1/migrating"}},l={},u=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3507],{56855:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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/6.1/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/troubleshooting.md",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/6.1/internals"},next:{title:"Migrating",permalink:"/docs/6.1/migrating"}},l={},u=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7810a993.5828a06b.js b/assets/js/7810a993.15789c24.js similarity index 99% rename from assets/js/7810a993.5828a06b.js rename to assets/js/7810a993.15789c24.js index f87a70d3f..15af14925 100644 --- a/assets/js/7810a993.5828a06b.js +++ b/assets/js/7810a993.15789c24.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9271],{19365:(e,n,t)=>{t.d(n,{A:()=>u});var a=t(96540),l=t(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:n,hidden:t,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),l=t(96540),r=t(20053),u=t(23104),o=t(56347),i=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.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:l}}=e;return{value:n,label:t,attributes:a,default:l}}))}function d(e){const{values:n,children:t}=e;return(0,l.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 m(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,o.W6)(),r=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.aZ)(r),(0,l.useCallback)((e=>{if(!r)return;const n=new URLSearchParams(a.location.search);n.set(r,e),a.replace({...a.location,search:n.toString()})}),[r,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.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(!m({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:r}))),[i,s]=g({queryString:t,groupId:a}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,r]=(0,c.Dv)(t);return[a,(0,l.useCallback)((e=>{t&&r.set(e)}),[t,r])]}({groupId:a}),h=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);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),y(e)}),[s,y,r]),tabValues:r}}var h=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==o&&(p(n),i(a))},m=e=>{let n=null;switch(e.key){case"Enter":d(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 l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:u}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const r=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,l.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function q(e){const n=y(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,n)),l.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(n)},e))}},84534:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=t(58168),l=(t(96540),t(15680)),r=(t(67443),t(11470)),u=t(19365);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-7.0.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-7.0.0/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/7.0.0/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/symfony-bundle-advanced.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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/7.0.0/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/7.0.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 g(e){let{components:n,...t}=e;return(0,l.yg)(m,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("div",{class:"alert alert--warning"},(0,l.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.yg)("p",null,"By settings ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.yg)("p",null,"The mutation below will log-in a user:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.yg)("p",null,"In Symfony, user objects implement ",(0,l.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.yg)("p",null,"If you want to get more fields, just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"You can now query this field using an ",(0,l.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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")))))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9271],{19365:(e,n,t)=>{t.d(n,{A:()=>u});var a=t(96540),l=t(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:n,hidden:t,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),l=t(96540),r=t(20053),u=t(23104),o=t(56347),i=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.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:l}}=e;return{value:n,label:t,attributes:a,default:l}}))}function d(e){const{values:n,children:t}=e;return(0,l.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 m(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,o.W6)(),r=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.aZ)(r),(0,l.useCallback)((e=>{if(!r)return;const n=new URLSearchParams(a.location.search);n.set(r,e),a.replace({...a.location,search:n.toString()})}),[r,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.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(!m({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:r}))),[i,s]=g({queryString:t,groupId:a}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,r]=(0,c.Dv)(t);return[a,(0,l.useCallback)((e=>{t&&r.set(e)}),[t,r])]}({groupId:a}),h=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);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),y(e)}),[s,y,r]),tabValues:r}}var h=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==o&&(p(n),i(a))},m=e=>{let n=null;switch(e.key){case"Enter":d(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 l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:u}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const r=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,l.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function q(e){const n=y(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,n)),l.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(n)},e))}},84534:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=t(58168),l=(t(96540),t(15680)),r=(t(67443),t(11470)),u=t(19365);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-7.0.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-7.0.0/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/7.0.0/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/symfony-bundle-advanced.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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/7.0.0/multiple-output-types"},next:{title:"Laravel specific features",permalink:"/docs/7.0.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 g(e){let{components:n,...t}=e;return(0,l.yg)(m,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("div",{class:"alert alert--warning"},(0,l.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.yg)("p",null,"By settings ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.yg)("p",null,"The mutation below will log-in a user:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.yg)("p",null,"In Symfony, user objects implement ",(0,l.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.yg)("p",null,"If you want to get more fields, just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"You can now query this field using an ",(0,l.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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")))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/78619623.4541130b.js b/assets/js/78619623.c6c9389a.js similarity index 99% rename from assets/js/78619623.4541130b.js rename to assets/js/78619623.c6c9389a.js index 99c757f88..f642988ba 100644 --- a/assets/js/78619623.4541130b.js +++ b/assets/js/78619623.c6c9389a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6209],{19365:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(96540),r=a(20053);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.A)(l.tabItem,i),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>x});var n=a(58168),r=a(96540),l=a(20053),i=a(23104),o=a(56347),u=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(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(!y({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,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return y({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),h(e)}),[s,h,l]),tabValues:l}}var f=a(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},y=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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:y,onClick:d},i,{className:(0,l.A)("tabs__item",g.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 T(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",g.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function x(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},24466:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/extend-type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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([[6209],{19365:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(96540),r=a(20053);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.A)(l.tabItem,i),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>x});var n=a(58168),r=a(96540),l=a(20053),i=a(23104),o=a(56347),u=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(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(!y({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,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return y({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),h(e)}),[s,h,l]),tabValues:l}}var f=a(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},y=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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:y,onClick:d},i,{className:(0,l.A)("tabs__item",g.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 T(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",g.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function x(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},24466:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/extend-type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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/78da31a1.5238c789.js b/assets/js/78da31a1.7208e28d.js similarity index 99% rename from assets/js/78da31a1.5238c789.js rename to assets/js/78da31a1.7208e28d.js index a5ee36bb6..650020887 100644 --- a/assets/js/78da31a1.5238c789.js +++ b/assets/js/78da31a1.7208e28d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4053],{19365:(e,n,t)=>{t.d(n,{A:()=>o});var a=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:n,hidden:t,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>I});var a=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function d(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 h(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??d(t);return function(e){const n=(0,s.X)(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 p(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,l.W6)(),i=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.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function m(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=h(e),[o,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(!p({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:i}))),[u,s]=g({queryString:t,groupId:a}),[d,m]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),y=(()=>{const e=u??d;return p({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),m(e)}),[s,m,i]),tabValues:i}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},p=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 r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function N(e){const n=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function I(e){const n=(0,y.A)();return r.createElement(N,(0,a.A)({key:String(n)},e))}},50039:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>g,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,r.yg)(p,(0,a.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.yg)("a",{parentName:"li",href:"/docs/4.1/fine-grained-security"},(0,r.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.yg)("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.yg)("br",null),"See ",(0,r.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.yg)("h2",{id:"logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.yg)("p",null,"GraphQLite exposes two annotations (",(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the query ",(0,r.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.1/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.yg)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4053],{19365:(e,n,t)=>{t.d(n,{A:()=>o});var a=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:n,hidden:t,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>I});var a=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function d(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 h(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??d(t);return function(e){const n=(0,s.X)(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 p(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,l.W6)(),i=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.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function m(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=h(e),[o,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(!p({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:i}))),[u,s]=g({queryString:t,groupId:a}),[d,m]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),y=(()=>{const e=u??d;return p({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),m(e)}),[s,m,i]),tabValues:i}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},p=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 r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function N(e){const n=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function I(e){const n=(0,y.A)();return r.createElement(N,(0,a.A)({key:String(n)},e))}},50039:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>g,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,r.yg)(p,(0,a.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.yg)("a",{parentName:"li",href:"/docs/4.1/fine-grained-security"},(0,r.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.yg)("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.yg)("br",null),"See ",(0,r.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.yg)("h2",{id:"logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.yg)("p",null,"GraphQLite exposes two annotations (",(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the query ",(0,r.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.1/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.yg)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7ade2db5.8dd4e724.js b/assets/js/7ade2db5.bbfffb1d.js similarity index 98% rename from assets/js/7ade2db5.8dd4e724.js rename to assets/js/7ade2db5.bbfffb1d.js index 73bac0ce5..ff8636ea0 100644 --- a/assets/js/7ade2db5.8dd4e724.js +++ b/assets/js/7ade2db5.bbfffb1d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1975],{8102:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var n=i(58168),r=(i(96540),i(15680));i(67443);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-8.0.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-8.0.0/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-8.0.0/implementing-security.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:"Operation complexity",permalink:"/docs/operation-complexity"}},c={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...i}=e;return(0,r.yg)(p,(0,n.A)({},l,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the #[Logged] attribute).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the #[Right] attribute).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1975],{8102:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var n=i(58168),r=(i(96540),i(15680));i(67443);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-8.0.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-8.0.0/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-8.0.0/implementing-security.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:"Operation complexity",permalink:"/docs/operation-complexity"}},c={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...i}=e;return(0,r.yg)(p,(0,n.A)({},l,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the #[Logged] attribute).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the #[Right] attribute).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7afb60b1.92665f44.js b/assets/js/7afb60b1.e108e213.js similarity index 99% rename from assets/js/7afb60b1.92665f44.js rename to assets/js/7afb60b1.e108e213.js index 79e8a91bb..d0533155d 100644 --- a/assets/js/7afb60b1.92665f44.js +++ b/assets/js/7afb60b1.e108e213.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4438],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>w});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),c=t(31682),u=t(89466);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,c.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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,c]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,u.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),c(e),y(e)}),[c,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),h=e=>{const n=e.currentTarget,t=u.indexOf(n),r=c[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=u.indexOf(e.currentTarget)+1;n=u[t]??u[0];break}case"ArrowLeft":{const t=u.indexOf(e.currentTarget)-1;n=u[t]??u[u.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.A)("tabs__item",f.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 v(e){const n=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function w(e){const n=(0,m.A)();return a.createElement(v,(0,r.A)({key:String(n)},e))}},9815:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>c,toc:()=>p});var r=t(58168),a=(t(96540),t(15680)),o=(t(67443),t(11470)),i=t(19365);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,c={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},u={},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 g(e){let{components:n,...t}=e;return(0,a.yg)(d,(0,r.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.3/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/4.3/laravel-package"},"Laravel"),")."),(0,a.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4438],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>w});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),c=t(31682),u=t(89466);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,c.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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,c]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,u.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),c(e),y(e)}),[c,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),h=e=>{const n=e.currentTarget,t=u.indexOf(n),r=c[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=u.indexOf(e.currentTarget)+1;n=u[t]??u[0];break}case"ArrowLeft":{const t=u.indexOf(e.currentTarget)-1;n=u[t]??u[u.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.A)("tabs__item",f.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 v(e){const n=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function w(e){const n=(0,m.A)();return a.createElement(v,(0,r.A)({key:String(n)},e))}},9815:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>c,toc:()=>p});var r=t(58168),a=(t(96540),t(15680)),o=(t(67443),t(11470)),i=t(19365);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,c={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},u={},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 g(e){let{components:n,...t}=e;return(0,a.yg)(d,(0,r.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.3/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/4.3/laravel-package"},"Laravel"),")."),(0,a.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7b417fb4.3878a6d8.js b/assets/js/7b417fb4.38721118.js similarity index 98% rename from assets/js/7b417fb4.3878a6d8.js rename to assets/js/7b417fb4.38721118.js index 6bcd5323b..80fc6592a 100644 --- a/assets/js/7b417fb4.3878a6d8.js +++ b/assets/js/7b417fb4.38721118.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9096],{47124:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>p,default:()=>y,frontMatter:()=>l,metadata:()=>o,toc:()=>u});var a=n(58168),i=(n(96540),n(15680));n(67443);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-8.0.0/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/multiple-output-types.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],r={toc:u},d="wrapper";function y(e){let{components:t,...n}=e;return(0,i.yg)(d,(0,a.A)({},r,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute."),(0,i.yg)("h2",{id:"example"},"Example"),(0,i.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,i.yg)("a",{parentName:"p",href:"/docs/external-type-declaration"},'"external" type')," mapping the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute."),(0,i.yg)("p",null,"First of all, we specify ",(0,i.yg)("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.yg)("p",null,"Then, we specify ",(0,i.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,i.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,i.yg)("p",null,"Finally, we can write our requests:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute to force the output type."),(0,i.yg)("p",null,"Is a result, when the end user calls the ",(0,i.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,i.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,i.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,i.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,i.yg)("p",null,"If you want to extend a type using the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,i.yg)("p",null,"So instead of writing:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,i.yg)("p",null,"you will write:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n')),(0,i.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute."))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9096],{47124:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>p,default:()=>y,frontMatter:()=>l,metadata:()=>o,toc:()=>u});var a=n(58168),i=(n(96540),n(15680));n(67443);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-8.0.0/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/multiple-output-types.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],r={toc:u},d="wrapper";function y(e){let{components:t,...n}=e;return(0,i.yg)(d,(0,a.A)({},r,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute."),(0,i.yg)("h2",{id:"example"},"Example"),(0,i.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,i.yg)("a",{parentName:"p",href:"/docs/external-type-declaration"},'"external" type')," mapping the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute."),(0,i.yg)("p",null,"First of all, we specify ",(0,i.yg)("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.yg)("p",null,"Then, we specify ",(0,i.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,i.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,i.yg)("p",null,"Finally, we can write our requests:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute to force the output type."),(0,i.yg)("p",null,"Is a result, when the end user calls the ",(0,i.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,i.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,i.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,i.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,i.yg)("p",null,"If you want to extend a type using the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,i.yg)("p",null,"So instead of writing:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,i.yg)("p",null,"you will write:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n')),(0,i.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute."))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7b54f5d5.53f40c9c.js b/assets/js/7b54f5d5.c9905422.js similarity index 99% rename from assets/js/7b54f5d5.53f40c9c.js rename to assets/js/7b54f5d5.c9905422.js index 8d0612291..18d837d69 100644 --- a/assets/js/7b54f5d5.53f40c9c.js +++ b/assets/js/7b54f5d5.c9905422.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4565],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),l=a(20053);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.A)(u.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>P});var n=a(58168),l=a(96540),u=a(20053),r=a(23104),i=a(56347),o=a(57485),p=a(31682),s=a(89466);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:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function d(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,p.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=d(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(!y({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]=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,u]=(0,s.Dv)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),g=(()=>{const e=o??c;return y({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),h(e)}),[p,h,u]),tabValues:u}}var g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),d=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(c(t),o(n))},y=e=>{let t=null;switch(e.key){case"Enter":d(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.A)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.A)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},r,{className:(0,u.A)("tabs__item",f.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 T(e){const t=h(e);return l.createElement("div",{className:(0,u.A)("tabs-container",f.tabList)},l.createElement(b,(0,n.A)({},e,t)),l.createElement(v,(0,n.A)({},e,t)))}function P(e){const t=(0,g.A)();return l.createElement(T,(0,n.A)({key:String(t)},e))}},71683:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>m,frontMatter:()=>i,metadata:()=>p,toc:()=>c});var n=a(58168),l=(a(96540),a(15680)),u=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},c=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:c},y="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/external-type-declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("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.yg)("p",null,"So instead of writing:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.yg)("p",null,"you will write:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4565],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),l=a(20053);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.A)(u.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>P});var n=a(58168),l=a(96540),u=a(20053),r=a(23104),i=a(56347),o=a(57485),p=a(31682),s=a(89466);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:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function d(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,p.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=d(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(!y({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]=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,u]=(0,s.Dv)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),g=(()=>{const e=o??c;return y({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),h(e)}),[p,h,u]),tabValues:u}}var g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),d=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(c(t),o(n))},y=e=>{let t=null;switch(e.key){case"Enter":d(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.A)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.A)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},r,{className:(0,u.A)("tabs__item",f.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 T(e){const t=h(e);return l.createElement("div",{className:(0,u.A)("tabs-container",f.tabList)},l.createElement(b,(0,n.A)({},e,t)),l.createElement(v,(0,n.A)({},e,t)))}function P(e){const t=(0,g.A)();return l.createElement(T,(0,n.A)({key:String(t)},e))}},71683:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>m,frontMatter:()=>i,metadata:()=>p,toc:()=>c});var n=a(58168),l=(a(96540),a(15680)),u=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},c=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:c},y="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/5.0/external-type-declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("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.yg)("p",null,"So instead of writing:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.yg)("p",null,"you will write:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7bf967bc.38b9cf53.js b/assets/js/7bf967bc.e0a8dc5d.js similarity index 98% rename from assets/js/7bf967bc.38b9cf53.js rename to assets/js/7bf967bc.e0a8dc5d.js index 150637f95..807980b5c 100644 --- a/assets/js/7bf967bc.38b9cf53.js +++ b/assets/js/7bf967bc.e0a8dc5d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5619],{6064:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>p,default:()=>c,frontMatter:()=>i,metadata:()=>u,toc:()=>s});var a=n(58168),l=(n(96540),n(15680));n(67443);const i={id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},p=void 0,u={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},o={},s=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],r={toc:s},d="wrapper";function c(e){let{components:t,...n}=e;return(0,l.yg)(d,(0,a.A)({},r,n,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/next/external-type-declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.yg)("p",null,"So instead of writing:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,l.yg)("p",null,"you will write:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n')),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5619],{6064:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>p,default:()=>c,frontMatter:()=>i,metadata:()=>u,toc:()=>s});var a=n(58168),l=(n(96540),n(15680));n(67443);const i={id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},p=void 0,u={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},o={},s=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],r={toc:s},d="wrapper";function c(e){let{components:t,...n}=e;return(0,l.yg)(d,(0,a.A)({},r,n,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/next/external-type-declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute and if this type is declared as non-default,\nyou need to target the type by name instead of by class."),(0,l.yg)("p",null,"So instead of writing:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,l.yg)("p",null,"you will write:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n')),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7c27e34c.578cf119.js b/assets/js/7c27e34c.1528c28d.js similarity index 95% rename from assets/js/7c27e34c.578cf119.js rename to assets/js/7c27e34c.1528c28d.js index cc86ddf9c..40926a0fb 100644 --- a/assets/js/7c27e34c.578cf119.js +++ b/assets/js/7c27e34c.1528c28d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9227],{74342:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>o,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>u});var r=a(58168),n=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,r.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,n.yg)("p",{align:"center"},(0,n.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,n.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,n.yg)("h2",{id:"features"},"Features"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,n.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony bundle available!"),(0,n.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, extendable types and more!")),(0,n.yg)("h2",{id:"basic-example"},"Basic example"),(0,n.yg)("p",null,"First, declare a query in your controller:"),(0,n.yg)("pre",null,(0,n.yg)("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.yg)("p",null,"Then, annotate the ",(0,n.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,n.yg)("pre",null,(0,n.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,n.yg)("pre",null,(0,n.yg)("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([[9227],{74342:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>o,contentTitle:()=>l,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>u});var r=a(58168),n=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,r.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,n.yg)("p",{align:"center"},(0,n.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,n.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,n.yg)("h2",{id:"features"},"Features"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,n.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony bundle available!"),(0,n.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, extendable types and more!")),(0,n.yg)("h2",{id:"basic-example"},"Basic example"),(0,n.yg)("p",null,"First, declare a query in your controller:"),(0,n.yg)("pre",null,(0,n.yg)("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.yg)("p",null,"Then, annotate the ",(0,n.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,n.yg)("pre",null,(0,n.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,n.yg)("pre",null,(0,n.yg)("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.661fb3a8.js b/assets/js/7e507331.7852fba8.js similarity index 98% rename from assets/js/7e507331.661fb3a8.js rename to assets/js/7e507331.7852fba8.js index bfae99197..d79f07874 100644 --- a/assets/js/7e507331.661fb3a8.js +++ b/assets/js/7e507331.7852fba8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2862],{39987:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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([[2862],{39987:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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.41e0e0e1.js b/assets/js/7e63a40e.a7d5d237.js similarity index 98% rename from assets/js/7e63a40e.41e0e0e1.js rename to assets/js/7e63a40e.a7d5d237.js index f304dbaee..f286259c0 100644 --- a/assets/js/7e63a40e.41e0e0e1.js +++ b/assets/js/7e63a40e.a7d5d237.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6984],{40467:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>t,metadata:()=>s,toc:()=>l});var n=i(58168),a=(i(96540),i(15680));i(67443);const t={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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,a.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,a.yg)("p",null,(0,a.yg)("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,a.yg)("p",null,"If your framework is compatible with ",(0,a.yg)("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,a.yg)("h2",{id:"installation"},"Installation"),(0,a.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,a.yg)("h2",{id:"requirements"},"Requirements"),(0,a.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,a.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,a.yg)("p",null,"GraphQLite relies on the ",(0,a.yg)("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,a.yg)("a",{parentName:"p",href:"/docs/4.1/other-frameworks"},"PSR-15 middleware"),"."),(0,a.yg)("h2",{id:"integration"},"Integration"),(0,a.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,a.yg)("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,a.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,a.yg)("p",null,(0,a.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,a.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,a.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"composer.json")),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"index.php")),(0,a.yg)("pre",null,(0,a.yg)("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([[6984],{40467:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>t,metadata:()=>s,toc:()=>l});var n=i(58168),a=(i(96540),i(15680));i(67443);const t={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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,a.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,a.yg)("p",null,(0,a.yg)("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,a.yg)("p",null,"If your framework is compatible with ",(0,a.yg)("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,a.yg)("h2",{id:"installation"},"Installation"),(0,a.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,a.yg)("h2",{id:"requirements"},"Requirements"),(0,a.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,a.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,a.yg)("p",null,"GraphQLite relies on the ",(0,a.yg)("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,a.yg)("a",{parentName:"p",href:"/docs/4.1/other-frameworks"},"PSR-15 middleware"),"."),(0,a.yg)("h2",{id:"integration"},"Integration"),(0,a.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,a.yg)("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,a.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,a.yg)("p",null,(0,a.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,a.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,a.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"composer.json")),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"index.php")),(0,a.yg)("pre",null,(0,a.yg)("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.68bd2d96.js b/assets/js/7ee46e43.29e7eea9.js similarity index 98% rename from assets/js/7ee46e43.68bd2d96.js rename to assets/js/7ee46e43.29e7eea9.js index 23e454a50..3979fc979 100644 --- a/assets/js/7ee46e43.68bd2d96.js +++ b/assets/js/7ee46e43.29e7eea9.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2400],{8239:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>p,contentTitle:()=>r,default:()=>y,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 y(t){let{components:e,...n}=t;return(0,i.yg)(c,(0,a.A)({},s,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"Let's admit you are developing an API that returns a list of cities around a location."),(0,i.yg)("p",null,"Your GraphQL query might look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,i.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,i.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,i.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,i.yg)("p",null,"In order to declare that type, in GraphQLite, we will declare a ",(0,i.yg)("strong",{parentName:"p"},"Factory"),"."),(0,i.yg)("p",null,"A ",(0,i.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,i.yg)("p",null,"Here is an example of factory:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,i.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,i.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,i.yg)("p",null,"A few important things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,i.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,i.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,i.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},'/**\n * @Factory(name="MyNewInputName")\n */\n')),(0,i.yg)("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."))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2400],{8239:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>p,contentTitle:()=>r,default:()=>y,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 y(t){let{components:e,...n}=t;return(0,i.yg)(c,(0,a.A)({},s,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"Let's admit you are developing an API that returns a list of cities around a location."),(0,i.yg)("p",null,"Your GraphQL query might look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,i.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,i.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,i.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,i.yg)("p",null,"In order to declare that type, in GraphQLite, we will declare a ",(0,i.yg)("strong",{parentName:"p"},"Factory"),"."),(0,i.yg)("p",null,"A ",(0,i.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,i.yg)("p",null,"Here is an example of factory:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,i.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,i.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,i.yg)("p",null,"A few important things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,i.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,i.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,i.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},'/**\n * @Factory(name="MyNewInputName")\n */\n')),(0,i.yg)("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."))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7f74c501.fe3b3a48.js b/assets/js/7f74c501.1de07200.js similarity index 98% rename from assets/js/7f74c501.fe3b3a48.js rename to assets/js/7f74c501.1de07200.js index 30b919184..70896769f 100644 --- a/assets/js/7f74c501.fe3b3a48.js +++ b/assets/js/7f74c501.1de07200.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[540],{13680:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>d,frontMatter:()=>r,metadata:()=>s,toc:()=>p});var n=a(58168),i=(a(96540),a(15680));a(67443);const r={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},o=void 0,s={unversionedId:"pagination",id:"version-8.0.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-8.0.0/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/pagination.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},l={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],u={toc:p},g="wrapper";function d(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,n.A)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,i.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,i.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,i.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,i.yg)("h2",{id:"installation"},"Installation"),(0,i.yg)("p",null,"You will need to install the ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,i.yg)("h2",{id:"usage"},"Usage"),(0,i.yg)("p",null,"In your query, simply return a class that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Notice that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,i.yg)("li",{parentName:"ul"},"you MUST add a ",(0,i.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,i.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,i.yg)("p",null,'The "count" field returns the ',(0,i.yg)("strong",{parentName:"p"},"total count")," of items."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[540],{13680:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>d,frontMatter:()=>r,metadata:()=>s,toc:()=>p});var n=a(58168),i=(a(96540),a(15680));a(67443);const r={id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},o=void 0,s={unversionedId:"pagination",id:"version-8.0.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-8.0.0/pagination.mdx",sourceDirName:".",slug:"/pagination",permalink:"/docs/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/pagination.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},l={},p=[{value:"Installation",id:"installation",level:2},{value:"Usage",id:"usage",level:2}],u={toc:p},g="wrapper";function d(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,n.A)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,i.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,i.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,i.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,i.yg)("h2",{id:"installation"},"Installation"),(0,i.yg)("p",null,"You will need to install the ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,i.yg)("h2",{id:"usage"},"Usage"),(0,i.yg)("p",null,"In your query, simply return a class that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Notice that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,i.yg)("li",{parentName:"ul"},"you MUST add a ",(0,i.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,i.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,i.yg)("p",null,'The "count" field returns the ',(0,i.yg)("strong",{parentName:"p"},"total count")," of items."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/820db038.99a98fa7.js b/assets/js/820db038.ab33b329.js similarity index 99% rename from assets/js/820db038.99a98fa7.js rename to assets/js/820db038.ab33b329.js index c972b1b12..429af4f27 100644 --- a/assets/js/820db038.99a98fa7.js +++ b/assets/js/820db038.ab33b329.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9742],{19365:(e,n,a)=>{a.d(n,{A:()=>s});var t=a(96540),r=a(20053);const i={tabItem:"tabItem_Ymn6"};function s(e){let{children:n,hidden:a,className:s}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,s),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),i=a(20053),s=a(23104),l=a(56347),p=a(57485),o=a(31682),u=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function d(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??c(a);return function(e){const n=(0,o.X)(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,a])}function m(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function y(e){let{queryString:n=!1,groupId:a}=e;const t=(0,l.W6)(),i=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(t.location.search);n.set(i,e),t.replace({...t.location,search:n.toString()})}),[i,t])]}function g(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,i=d(e),[s,l]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!m({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:i}))),[p,o]=y({queryString:a,groupId:t}),[c,g]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,i]=(0,u.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:t}),h=(()=>{const e=p??c;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{h&&l(h)}),[h]);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),g(e)}),[o,g,i]),tabValues:i}}var h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:p,tabValues:o}=e;const u=[],{blockElementScrollPositionUntilNextRender:c}=(0,s.a_)(),d=e=>{const n=e.currentTarget,a=u.indexOf(n),t=o[a].value;t!==l&&(c(n),p(t))},m=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=u.indexOf(e.currentTarget)+1;n=u[a]??u[0];break}case"ArrowLeft":{const a=u.indexOf(e.currentTarget)-1;n=u[a]??u[u.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":a},n)},o.map((e=>{let{value:n,label:a,attributes:s}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:m,onClick:d},s,{className:(0,i.A)("tabs__item",f.tabItem,s?.className,{"tabs__item--active":l===n})}),a??n)})))}function N(e){let{lazy:n,children:a,selectedValue:t}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=i.find((e=>e.props.value===t));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==t}))))}function v(e){const n=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(N,(0,t.A)({},e,n)))}function T(e){const n=(0,h.A)();return r.createElement(v,(0,t.A)({key:String(n)},e))}},4466:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>o});var t=a(58168),r=(a(96540),a(15680));a(67443),a(11470),a(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"docs",previous:{title:"Mutations",permalink:"/docs/6.1/mutations"},next:{title:"Autowiring services",permalink:"/docs/6.1/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:n,...a}=e;return(0,r.yg)(c,(0,t.A)({},u,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"As explained in the ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.1/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,r.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,r.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"string")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"int")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"bool")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"float"))),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,r.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n')),(0,r.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,r.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,r.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,r.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,r.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,r.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,r.yg)("p",null,"GraphQL comes with a native ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,r.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,r.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n')),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,r.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,r.yg)("p",null,"You can learn more about forcing output types in the ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.1/custom-types"},"custom types section"),"."),(0,r.yg)("h3",{id:"id-class"},"ID class"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n")),(0,r.yg)("p",null,"Note that you can also use the ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,r.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,r.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,r.yg)("p",null,"When used as an output type, ",(0,r.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,r.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,r.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,r.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,r.yg)("div",{class:"alert alert--danger"},"PHP ",(0,r.yg)("code",null,"DateTime")," type is not supported."),(0,r.yg)("h2",{id:"union-types"},"Union types"),(0,r.yg)("p",null,"You can create a GraphQL union type ",(0,r.yg)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,r.yg)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,r.yg)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"name")," property on the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,r.yg)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,r.yg)("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.yg)("p",null,(0,r.yg)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,r.yg)("p",null,"Now, any class extending the ",(0,r.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,r.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,r.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will add the ",(0,r.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,r.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,r.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,r.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,r.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,r.yg)("p",null,"If you need more types, you can check the ",(0,r.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,r.yg)("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([[9742],{19365:(e,n,a)=>{a.d(n,{A:()=>s});var t=a(96540),r=a(20053);const i={tabItem:"tabItem_Ymn6"};function s(e){let{children:n,hidden:a,className:s}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,s),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),i=a(20053),s=a(23104),l=a(56347),p=a(57485),o=a(31682),u=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function d(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??c(a);return function(e){const n=(0,o.X)(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,a])}function m(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function y(e){let{queryString:n=!1,groupId:a}=e;const t=(0,l.W6)(),i=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(t.location.search);n.set(i,e),t.replace({...t.location,search:n.toString()})}),[i,t])]}function g(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,i=d(e),[s,l]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!m({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:i}))),[p,o]=y({queryString:a,groupId:t}),[c,g]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,i]=(0,u.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:t}),h=(()=>{const e=p??c;return m({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{h&&l(h)}),[h]);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),g(e)}),[o,g,i]),tabValues:i}}var h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:p,tabValues:o}=e;const u=[],{blockElementScrollPositionUntilNextRender:c}=(0,s.a_)(),d=e=>{const n=e.currentTarget,a=u.indexOf(n),t=o[a].value;t!==l&&(c(n),p(t))},m=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=u.indexOf(e.currentTarget)+1;n=u[a]??u[0];break}case"ArrowLeft":{const a=u.indexOf(e.currentTarget)-1;n=u[a]??u[u.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":a},n)},o.map((e=>{let{value:n,label:a,attributes:s}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:m,onClick:d},s,{className:(0,i.A)("tabs__item",f.tabItem,s?.className,{"tabs__item--active":l===n})}),a??n)})))}function N(e){let{lazy:n,children:a,selectedValue:t}=e;const i=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=i.find((e=>e.props.value===t));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map(((e,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==t}))))}function v(e){const n=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(N,(0,t.A)({},e,n)))}function T(e){const n=(0,h.A)();return r.createElement(v,(0,t.A)({key:String(n)},e))}},4466:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>o});var t=a(58168),r=(a(96540),a(15680));a(67443),a(11470),a(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"type-mapping",title:"Type mapping",sidebar_label:"Type mapping"},sidebar:"docs",previous:{title:"Mutations",permalink:"/docs/6.1/mutations"},next:{title:"Autowiring services",permalink:"/docs/6.1/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:n,...a}=e;return(0,r.yg)(c,(0,t.A)({},u,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"As explained in the ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.1/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,r.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,r.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"string")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"int")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"bool")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"float"))),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,r.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n')),(0,r.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,r.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,r.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,r.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,r.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,r.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,r.yg)("p",null,"GraphQL comes with a native ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,r.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,r.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n')),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,r.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,r.yg)("p",null,"You can learn more about forcing output types in the ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.1/custom-types"},"custom types section"),"."),(0,r.yg)("h3",{id:"id-class"},"ID class"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n")),(0,r.yg)("p",null,"Note that you can also use the ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,r.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,r.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,r.yg)("p",null,"When used as an output type, ",(0,r.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,r.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,r.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,r.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,r.yg)("div",{class:"alert alert--danger"},"PHP ",(0,r.yg)("code",null,"DateTime")," type is not supported."),(0,r.yg)("h2",{id:"union-types"},"Union types"),(0,r.yg)("p",null,"You can create a GraphQL union type ",(0,r.yg)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,r.yg)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,r.yg)("p",null,"PHP 8.1 introduced native support for Enums. GraphQLite now also supports native enums as of version 5.1."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: Status!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"name")," property on the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'namespace Model\\User;\n\n#[Type(name: "UserStatus")]\nenum Status: string\n{\n // ...\n}\n')),(0,r.yg)("h3",{id:"enum-types-with-myclabsphp-enum"},"Enum types with myclabs/php-enum"),(0,r.yg)("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.yg)("p",null,(0,r.yg)("em",{parentName:"p"},"Prior to version 5.1, GraphQLite only supported Enums through the 3rd party library, ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,r.yg)("p",null,"Now, any class extending the ",(0,r.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,r.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,r.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation. Note that a description (reason) is required for the annotation to be rendered."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will add the ",(0,r.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,r.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,r.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,r.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,r.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,r.yg)("p",null,"If you need more types, you can check the ",(0,r.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,r.yg)("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/8223875c.75de77e7.js b/assets/js/8223875c.697480e4.js similarity index 99% rename from assets/js/8223875c.75de77e7.js rename to assets/js/8223875c.697480e4.js index 2890b23ff..5198b3110 100644 --- a/assets/js/8223875c.75de77e7.js +++ b/assets/js/8223875c.697480e4.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6487],{56621:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>g,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=t(58168),r=(t(96540),t(15680));t(67443);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-8.0.0/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/argument-resolving.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom attributes",permalink:"/docs/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/extend-input-type"}},s={},p=[{value:"Attributes parsing",id:"attributes-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},u="wrapper";function g(e){let{components:a,...t}=e;return(0,r.yg)(u,(0,n.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Autowire]")," attribute")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Validate]")," attribute (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"attributes-parsing"},"Attributes parsing"),(0,r.yg)("p",null,"If you plan to use attributes while resolving arguments, your attribute class should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Autowire]"),"."),(0,r.yg)("p",null,"We only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The class looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this attribute to autowire a service from the container into a given parameter of a field/query/mutation.\n *\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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6487],{56621:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>g,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var n=t(58168),r=(t(96540),t(15680));t(67443);const i={id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},o=void 0,l={unversionedId:"argument-resolving",id:"version-8.0.0/argument-resolving",title:"Extending argument resolving",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/argument-resolving.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom attributes",permalink:"/docs/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/extend-input-type"}},s={},p=[{value:"Attributes parsing",id:"attributes-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},u="wrapper";function g(e){let{components:a,...t}=e;return(0,r.yg)(u,(0,n.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Autowire]")," attribute")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Validate]")," attribute (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"attributes-parsing"},"Attributes parsing"),(0,r.yg)("p",null,"If you plan to use attributes while resolving arguments, your attribute class should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Autowire]"),"."),(0,r.yg)("p",null,"We only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The class looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use Attribute;\n\n/**\n * Use this attribute to autowire a service from the container into a given parameter of a field/query/mutation.\n *\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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("p",null,'If you are using the Symfony bundle, you can tag the service as "graphql.parameter_middleware".'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/822cd419.cca2946f.js b/assets/js/822cd419.ca58e052.js similarity index 98% rename from assets/js/822cd419.cca2946f.js rename to assets/js/822cd419.ca58e052.js index eccb75f26..f8ab186e3 100644 --- a/assets/js/822cd419.cca2946f.js +++ b/assets/js/822cd419.ca58e052.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7382],{87445:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.1/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/6.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,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/6.1/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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([[7382],{87445:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.1/laravel-package"},next:{title:"Other frameworks / No framework",permalink:"/docs/6.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,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/6.1/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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.31f38c8d.js b/assets/js/82395e72.49c98b08.js similarity index 99% rename from assets/js/82395e72.31f38c8d.js rename to assets/js/82395e72.49c98b08.js index a83af72e6..4b8863234 100644 --- a/assets/js/82395e72.31f38c8d.js +++ b/assets/js/82395e72.49c98b08.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3576],{19365:(e,a,t)=>{t.d(a,{A:()=>o});var n=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:a,hidden:t,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>V});var n=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),s=t(57485),u=t(31682),d=t(89466);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function c(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??p(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function m(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:t}=e;const n=(0,l.W6)(),i=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const a=new URLSearchParams(n.location.search);a.set(i,e),n.replace({...n.location,search:a.toString()})}),[i,n])]}function y(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!m({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:i}))),[s,u]=h({queryString:t,groupId:n}),[p,y]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,i]=(0,d.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:n}),g=(()=>{const e=s??p;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),y(e)}),[u,y,i]),tabValues:i}}var g=t(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:a,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),c=e=>{const a=e.currentTarget,t=d.indexOf(a),n=u[t].value;n!==l&&(p(a),s(n))},m=e=>{let a=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const t=d.indexOf(e.currentTarget)+1;a=d[t]??d[0];break}case"ArrowLeft":{const t=d.indexOf(e.currentTarget)-1;a=d[t]??d[d.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.A)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=y(e);return r.createElement("div",{className:(0,i.A)("tabs-container",v.tabList)},r.createElement(f,(0,n.A)({},e,a)),r.createElement(b,(0,n.A)({},e,a)))}function V(e){const a=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},39698:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,r.yg)(m,(0,n.A)({},c,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,r.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.yg)("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.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.yg)("p",null,"You can also pass an array to the ",(0,r.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.yg)("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([[3576],{19365:(e,a,t)=>{t.d(a,{A:()=>o});var n=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:a,hidden:t,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>V});var n=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),s=t(57485),u=t(31682),d=t(89466);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function c(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??p(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function m(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:t}=e;const n=(0,l.W6)(),i=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const a=new URLSearchParams(n.location.search);a.set(i,e),n.replace({...n.location,search:a.toString()})}),[i,n])]}function y(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!m({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:i}))),[s,u]=h({queryString:t,groupId:n}),[p,y]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,i]=(0,d.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:n}),g=(()=>{const e=s??p;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),y(e)}),[u,y,i]),tabValues:i}}var g=t(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:a,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),c=e=>{const a=e.currentTarget,t=d.indexOf(a),n=u[t].value;n!==l&&(p(a),s(n))},m=e=>{let a=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const t=d.indexOf(e.currentTarget)+1;a=d[t]??d[0];break}case"ArrowLeft":{const t=d.indexOf(e.currentTarget)-1;a=d[t]??d[d.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.A)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=y(e);return r.createElement("div",{className:(0,i.A)("tabs-container",v.tabList)},r.createElement(f,(0,n.A)({},e,a)),r.createElement(b,(0,n.A)({},e,a)))}function V(e){const a=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},39698:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,r.yg)(m,(0,n.A)({},c,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,r.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.yg)("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.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.yg)("p",null,"You can also pass an array to the ",(0,r.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.yg)("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.c85f1b45.js b/assets/js/8299d165.a4ac47c1.js similarity index 99% rename from assets/js/8299d165.c85f1b45.js rename to assets/js/8299d165.a4ac47c1.js index 8adce68b5..1bd141a44 100644 --- a/assets/js/8299d165.c85f1b45.js +++ b/assets/js/8299d165.a4ac47c1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6009],{19365:(e,a,n)=>{n.d(a,{A:()=>i});var t=n(96540),r=n(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:a,hidden:n,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:n},a)}},11470:(e,a,n)=>{n.d(a,{A:()=>T});var t=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),p=n(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:n,attributes:t,default:r}}=e;return{value:a,label:n,attributes:t,default:r}}))}function d(e){const{values:a,children:n}=e;return(0,r.useMemo)((()=>{const e=a??c(n);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,n])}function g(e){let{value:a,tabValues:n}=e;return n.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:n}=e;const t=(0,o.W6)(),l=function(e){let{queryString:a=!1,groupId:n}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:n});return[(0,s.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(t.location.search);a.set(l,e),t.replace({...t.location,search:a.toString()})}),[l,t])]}function m(e){const{defaultValue:a,queryString:n=!1,groupId:t}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const t=n.find((e=>e.default))??n[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:a,tabValues:l}))),[s,u]=h({queryString:n,groupId:t}),[c,m]=function(e){let{groupId:a}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(a),[t,l]=(0,p.Dv)(n);return[t,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:t}),y=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,l]),tabValues:l}}var y=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const a=e.currentTarget,n=p.indexOf(a),t=u[n].value;t!==o&&(c(a),s(t))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;a=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;a=p[n]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":n},a)},u.map((e=>{let{value:a,label:n,attributes:i}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===a})}),n??a)})))}function b(e){let{lazy:a,children:n,selectedValue:t}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(a){const e=l.find((e=>e.props.value===t));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==t}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(v,(0,t.A)({},e,a)),r.createElement(b,(0,t.A)({},e,a)))}function T(e){const a=(0,y.A)();return r.createElement(w,(0,t.A)({key:String(a)},e))}},27736:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var t=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},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},g="wrapper";function h(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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'))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6009],{19365:(e,a,n)=>{n.d(a,{A:()=>i});var t=n(96540),r=n(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:a,hidden:n,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:n},a)}},11470:(e,a,n)=>{n.d(a,{A:()=>T});var t=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),p=n(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:n,attributes:t,default:r}}=e;return{value:a,label:n,attributes:t,default:r}}))}function d(e){const{values:a,children:n}=e;return(0,r.useMemo)((()=>{const e=a??c(n);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,n])}function g(e){let{value:a,tabValues:n}=e;return n.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:n}=e;const t=(0,o.W6)(),l=function(e){let{queryString:a=!1,groupId:n}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:n});return[(0,s.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(t.location.search);a.set(l,e),t.replace({...t.location,search:a.toString()})}),[l,t])]}function m(e){const{defaultValue:a,queryString:n=!1,groupId:t}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const t=n.find((e=>e.default))??n[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:a,tabValues:l}))),[s,u]=h({queryString:n,groupId:t}),[c,m]=function(e){let{groupId:a}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(a),[t,l]=(0,p.Dv)(n);return[t,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:t}),y=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,l]),tabValues:l}}var y=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const a=e.currentTarget,n=p.indexOf(a),t=u[n].value;t!==o&&(c(a),s(t))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;a=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;a=p[n]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":n},a)},u.map((e=>{let{value:a,label:n,attributes:i}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===a})}),n??a)})))}function b(e){let{lazy:a,children:n,selectedValue:t}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(a){const e=l.find((e=>e.props.value===t));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==t}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(v,(0,t.A)({},e,a)),r.createElement(b,(0,t.A)({},e,a)))}function T(e){const a=(0,y.A)();return r.createElement(w,(0,t.A)({key:String(a)},e))}},27736:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var t=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},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},g="wrapper";function h(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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'))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/843ebfb4.b37baa9b.js b/assets/js/843ebfb4.2328701a.js similarity index 99% rename from assets/js/843ebfb4.b37baa9b.js rename to assets/js/843ebfb4.2328701a.js index 57a411699..cb6fb4975 100644 --- a/assets/js/843ebfb4.b37baa9b.js +++ b/assets/js/843ebfb4.2328701a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1585],{50237:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>y,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(58168),i=(a(96540),a(15680));a(67443);const o={id:"validation",title:"Validation",sidebar_label:"User input validation"},r=void 0,l={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},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 / subscription / factory ...",id:"using-the-validator-directly-on-a-query--mutation--subscription--factory-",level:3},{value:"Custom InputType Validation",id:"custom-inputtype-validation",level:2}],p={toc:d},u="wrapper";function y(e){let{components:t,...a}=e;return(0,i.yg)(u,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.yg)("pre",{parentName:"li"},(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.yg)("p",null,"Usually, when you use the Symfony validator component, you put attributes in your entities and you validate those entities\nusing the ",(0,i.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.yg)("pre",null,(0,i.yg)("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 }\n }\n ]\n}\n')),(0,i.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--subscription--factory-"},"Using the validator directly on a query / mutation / subscription / factory ..."),(0,i.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,i.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.yg)("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.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Assertion]")," attribute to validate directly the user input."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\GraphQLite\\Validator\\Annotations\\Assertion;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\n#[Query]\n#[Assertion(for: "email", constraint: new Assert\\Email())]\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,i.yg)("p",null,'Notice that the "constraint" parameter contains an attribute (it is an attribute wrapped in an attribute).'),(0,i.yg)("p",null,"You can also pass an array to the ",(0,i.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Assertion(for: "email", constraint: [new Assert\\NotBlack(), new Assert\\Email()])]\n')),(0,i.yg)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.yg)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.yg)("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.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("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.yg)("p",null,"To get started with validation on input types defined by an ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute, you'll first need to register your validator with the ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"$factory = new SchemaFactory($cache, $this->container);\n$factory->addNamespace('App');\n// Register your validator\n$factory->setInputTypeValidator($this->container->get('your_validator'));\n$factory->createSchema();\n")),(0,i.yg)("p",null,"Your input type validator must implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.yg)("inlineCode",{parentName:"p"},"validate")," method. For example, you might use Symfony's attribute 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.yg)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.yg)("p",null,"You'll notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.yg)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.yg)("p",null,"Also available is the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.yg)("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."))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1585],{50237:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>y,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(58168),i=(a(96540),a(15680));a(67443);const o={id:"validation",title:"Validation",sidebar_label:"User input validation"},r=void 0,l={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},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 / subscription / factory ...",id:"using-the-validator-directly-on-a-query--mutation--subscription--factory-",level:3},{value:"Custom InputType Validation",id:"custom-inputtype-validation",level:2}],p={toc:d},u="wrapper";function y(e){let{components:t,...a}=e;return(0,i.yg)(u,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.yg)("pre",{parentName:"li"},(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.yg)("p",null,"Usually, when you use the Symfony validator component, you put attributes in your entities and you validate those entities\nusing the ",(0,i.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.yg)("pre",null,(0,i.yg)("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 }\n }\n ]\n}\n')),(0,i.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--subscription--factory-"},"Using the validator directly on a query / mutation / subscription / factory ..."),(0,i.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,i.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.yg)("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.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Assertion]")," attribute to validate directly the user input."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\GraphQLite\\Validator\\Annotations\\Assertion;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\n#[Query]\n#[Assertion(for: "email", constraint: new Assert\\Email())]\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,i.yg)("p",null,'Notice that the "constraint" parameter contains an attribute (it is an attribute wrapped in an attribute).'),(0,i.yg)("p",null,"You can also pass an array to the ",(0,i.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Assertion(for: "email", constraint: [new Assert\\NotBlack(), new Assert\\Email()])]\n')),(0,i.yg)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.yg)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.yg)("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.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("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.yg)("p",null,"To get started with validation on input types defined by an ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute, you'll first need to register your validator with the ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"$factory = new SchemaFactory($cache, $this->container);\n$factory->addNamespace('App');\n// Register your validator\n$factory->setInputTypeValidator($this->container->get('your_validator'));\n$factory->createSchema();\n")),(0,i.yg)("p",null,"Your input type validator must implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.yg)("inlineCode",{parentName:"p"},"validate")," method. For example, you might use Symfony's attribute 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.yg)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.yg)("p",null,"You'll notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.yg)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.yg)("p",null,"Also available is the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.yg)("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."))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/85339969.02e8c648.js b/assets/js/85339969.b14499df.js similarity index 99% rename from assets/js/85339969.02e8c648.js rename to assets/js/85339969.b14499df.js index 25163b601..5b61d0bb5 100644 --- a/assets/js/85339969.02e8c648.js +++ b/assets/js/85339969.b14499df.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7141],{92617:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/5.0/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/5.0/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7141],{92617:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/5.0/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/5.0/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/859fcda7.5fa26c20.js b/assets/js/859fcda7.b533069a.js similarity index 97% rename from assets/js/859fcda7.5fa26c20.js rename to assets/js/859fcda7.b533069a.js index 8aba00574..154de3828 100644 --- a/assets/js/859fcda7.5fa26c20.js +++ b/assets/js/859fcda7.b533069a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9810],{95499:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],g={toc:l},c="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},g,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/universal_service_providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9810],{95499:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],g={toc:l},c="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},g,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/universal_service_providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/85c72337.54300e03.js b/assets/js/85c72337.7ed996b5.js similarity index 99% rename from assets/js/85c72337.54300e03.js rename to assets/js/85c72337.7ed996b5.js index bce122852..aca1b7603 100644 --- a/assets/js/85c72337.54300e03.js +++ b/assets/js/85c72337.7ed996b5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5779],{19365:(e,n,t)=>{t.d(n,{A:()=>u});var a=t(96540),l=t(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:n,hidden:t,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),l=t(96540),r=t(20053),u=t(23104),o=t(56347),i=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.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:l}}=e;return{value:n,label:t,attributes:a,default:l}}))}function d(e){const{values:n,children:t}=e;return(0,l.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 m(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,o.W6)(),r=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.aZ)(r),(0,l.useCallback)((e=>{if(!r)return;const n=new URLSearchParams(a.location.search);n.set(r,e),a.replace({...a.location,search:n.toString()})}),[r,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.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(!m({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:r}))),[i,s]=g({queryString:t,groupId:a}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,r]=(0,c.Dv)(t);return[a,(0,l.useCallback)((e=>{t&&r.set(e)}),[t,r])]}({groupId:a}),h=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);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),y(e)}),[s,y,r]),tabValues:r}}var h=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==o&&(p(n),i(a))},m=e=>{let n=null;switch(e.key){case"Enter":d(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 l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:u}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const r=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,l.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function q(e){const n=y(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,n)),l.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(n)},e))}},25290:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=t(58168),l=(t(96540),t(15680)),r=(t(67443),t(11470)),u=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,l.yg)(m,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("div",{class:"alert alert--warning"},(0,l.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.yg)("p",null,"By settings ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.yg)("p",null,"The mutation below will log-in a user:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.yg)("p",null,"In Symfony, user objects implement ",(0,l.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.yg)("p",null,"If you want to get more fields, just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"You can now query this field using an ",(0,l.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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")))))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5779],{19365:(e,n,t)=>{t.d(n,{A:()=>u});var a=t(96540),l=t(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:n,hidden:t,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),l=t(96540),r=t(20053),u=t(23104),o=t(56347),i=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.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:l}}=e;return{value:n,label:t,attributes:a,default:l}}))}function d(e){const{values:n,children:t}=e;return(0,l.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 m(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,o.W6)(),r=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.aZ)(r),(0,l.useCallback)((e=>{if(!r)return;const n=new URLSearchParams(a.location.search);n.set(r,e),a.replace({...a.location,search:n.toString()})}),[r,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.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(!m({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:r}))),[i,s]=g({queryString:t,groupId:a}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,r]=(0,c.Dv)(t);return[a,(0,l.useCallback)((e=>{t&&r.set(e)}),[t,r])]}({groupId:a}),h=(()=>{const e=i??p;return m({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);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),y(e)}),[s,y,r]),tabValues:r}}var h=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==o&&(p(n),i(a))},m=e=>{let n=null;switch(e.key){case"Enter":d(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 l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:u}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>c.push(e),onKeyDown:m,onClick:d},u,{className:(0,r.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const r=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,l.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function q(e){const n=y(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,n)),l.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(n)},e))}},25290:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=t(58168),l=(t(96540),t(15680)),r=(t(67443),t(11470)),u=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,l.yg)(m,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("div",{class:"alert alert--warning"},(0,l.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-bundle"},"Github repository"),"."),(0,l.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.yg)("p",null,"By settings ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.yg)("p",null,"The mutation below will log-in a user:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.yg)("p",null,"In Symfony, user objects implement ",(0,l.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.yg)("p",null,"If you want to get more fields, just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"You can now query this field using an ",(0,l.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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")))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/87089bce.9e057df3.js b/assets/js/87089bce.a9173e85.js similarity index 99% rename from assets/js/87089bce.9e057df3.js rename to assets/js/87089bce.a9173e85.js index 4e932203a..ede3f1c47 100644 --- a/assets/js/87089bce.9e057df3.js +++ b/assets/js/87089bce.a9173e85.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4253],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var t=a(96540),r=a(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),l=a(20053),i=a(23104),s=a(56347),p=a(57485),c=a(31682),o=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function m(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function d(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function y(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[p,c]=g({queryString:a,groupId:t}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{h&&s(h)}),[h]);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),y(e)}),[c,y,l]),tabValues:l}}var h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=c[a].value;t!==s&&(u(n),p(t))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return r.createElement("li",(0,t.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function N(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(v,(0,t.A)({},e,n)))}function T(e){const n=(0,h.A)();return r.createElement(N,(0,t.A)({key:String(n)},e))}},132:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>g,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var t=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"version-7.0.0/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-7.0.0/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/7.0.0/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/inheritance-interfaces.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"docs",previous:{title:"Input types",permalink:"/docs/7.0.0/input-types"},next:{title:"Error handling",permalink:"/docs/7.0.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 g(e){let{components:n,...a}=e;return(0,r.yg)(d,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.yg)("p",null,"Written in ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.yg)("p",null,"The GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.yg)("p",null,"This will translate in GraphQL schema as:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.yg)("p",null,"Please note that you do not need to put the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.yg)("p",null,"You don't have to explicitly put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4253],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var t=a(96540),r=a(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),l=a(20053),i=a(23104),s=a(56347),p=a(57485),c=a(31682),o=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function m(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function d(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function y(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[p,c]=g({queryString:a,groupId:t}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{h&&s(h)}),[h]);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),y(e)}),[c,y,l]),tabValues:l}}var h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=c[a].value;t!==s&&(u(n),p(t))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return r.createElement("li",(0,t.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function N(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(v,(0,t.A)({},e,n)))}function T(e){const n=(0,h.A)();return r.createElement(N,(0,t.A)({key:String(n)},e))}},132:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>g,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var t=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);const s={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},p=void 0,c={unversionedId:"inheritance-interfaces",id:"version-7.0.0/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-7.0.0/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/7.0.0/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/inheritance-interfaces.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},sidebar:"docs",previous:{title:"Input types",permalink:"/docs/7.0.0/input-types"},next:{title:"Error handling",permalink:"/docs/7.0.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 g(e){let{components:n,...a}=e;return(0,r.yg)(d,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.yg)("p",null,"Written in ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.yg)("p",null,"The GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.yg)("p",null,"This will translate in GraphQL schema as:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.yg)("p",null,"Please note that you do not need to put the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.yg)("p",null,"You don't have to explicitly put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/8913b51a.bd94c17c.js b/assets/js/8913b51a.e13c7382.js similarity index 98% rename from assets/js/8913b51a.bd94c17c.js rename to assets/js/8913b51a.e13c7382.js index 5820aeb31..adad63b20 100644 --- a/assets/js/8913b51a.bd94c17c.js +++ b/assets/js/8913b51a.e13c7382.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7575],{71120:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>n,default:()=>h,frontMatter:()=>i,metadata:()=>r,toc:()=>s});var o=t(58168),l=(t(96540),t(15680));t(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"docs",previous:{title:"Prefetching records",permalink:"/docs/6.1/prefetch-method"},next:{title:"Pagination",permalink:"/docs/6.1/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:a,...t}=e;return(0,l.yg)(d,(0,o.A)({},u,t,{components:a,mdxType:"MDXLayout"}),(0,l.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,l.yg)("h2",{id:"installation"},"Installation"),(0,l.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,l.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,l.yg)("p",null,"You must start by installing this package:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,l.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,l.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,l.yg)("p",null,"In order to use this, you must first be sure that the ",(0,l.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,l.yg)("p",null,"Simply add ",(0,l.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,l.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,l.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,l.yg)("h2",{id:"usage"},"Usage"),(0,l.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,l.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,l.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,l.yg)("pre",null,(0,l.yg)("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([[7575],{71120:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>n,default:()=>h,frontMatter:()=>i,metadata:()=>r,toc:()=>s});var o=t(58168),l=(t(96540),t(15680));t(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"docs",previous:{title:"Prefetching records",permalink:"/docs/6.1/prefetch-method"},next:{title:"Pagination",permalink:"/docs/6.1/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:a,...t}=e;return(0,l.yg)(d,(0,o.A)({},u,t,{components:a,mdxType:"MDXLayout"}),(0,l.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,l.yg)("h2",{id:"installation"},"Installation"),(0,l.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,l.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,l.yg)("p",null,"You must start by installing this package:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,l.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,l.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,l.yg)("p",null,"In order to use this, you must first be sure that the ",(0,l.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,l.yg)("p",null,"Simply add ",(0,l.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,l.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,l.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,l.yg)("h2",{id:"usage"},"Usage"),(0,l.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,l.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,l.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,l.yg)("pre",null,(0,l.yg)("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.1a554faa.js b/assets/js/89cae3a7.ffe79b51.js similarity index 99% rename from assets/js/89cae3a7.1a554faa.js rename to assets/js/89cae3a7.ffe79b51.js index 59f3feb5b..f66c2fc9a 100644 --- a/assets/js/89cae3a7.1a554faa.js +++ b/assets/js/89cae3a7.ffe79b51.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7858],{81295:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var a=n(58168),i=(n(96540),n(15680));n(67443);const o={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},r=void 0,l={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 attribute 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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},s={},u=[{value:"#[Type] attribute with the class attribute",id:"type-attribute-with-the-class-attribute",level:2},{value:"#[SourceField] attribute",id:"sourcefield-attribute",level:2},{value:"#[MagicField] attribute",id:"magicfield-attribute",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without attributes)",id:"declaring-fields-dynamically-without-attributes",level:2}],d={toc:u},p="wrapper";function c(e){let{components:t,...n}=e;return(0,i.yg)(p,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In some cases, you cannot or do not want to put an attribute on a domain class."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,i.yg)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with attributes from the view layer"),(0,i.yg)("li",{parentName:"ul"},"etc.")),(0,i.yg)("h2",{id:"type-attribute-with-the-class-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"#[Type]")," attribute with the ",(0,i.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,i.yg)("p",null,"GraphQLite allows you to use a ",(0,i.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute with the ",(0,i.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,i.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("p",null,"In methods with a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute, the first parameter is the ",(0,i.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,i.yg)("h2",{id:"sourcefield-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"#[SourceField]")," attribute"),(0,i.yg)("p",null,"If you don't want to rewrite all ",(0,i.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,i.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,i.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,i.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,i.yg)("h2",{id:"magicfield-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"#[MagicField]")," attribute"),(0,i.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,i.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[MagicField]")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,i.yg)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,i.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,i.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,i.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,i.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" argument.'),(0,i.yg)("pre",null,(0,i.yg)("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#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price", annotations: [new Logged(), new Right("CAN_ACCESS_Price"), new FailWith(null)])]\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,i.yg)("p",null,"Any attributes described in the ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/authentication-authorization"},"Authentication and authorization page"),", or any attribute this is actually a ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/field-middlewares"},'"field middleware"')," can be used in the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]"),' "annotations" argument.'),(0,i.yg)("h2",{id:"declaring-fields-dynamically-without-attributes"},"Declaring fields dynamically (without attributes)"),(0,i.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," attributes at development time.\nIf you need to decide the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," at runtime, you can implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,i.yg)("pre",null,(0,i.yg)("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', 'annotations'=>[new Logged()]]),\n ];\n } else {\n return [];\n }\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7858],{81295:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var a=n(58168),i=(n(96540),n(15680));n(67443);const o={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},r=void 0,l={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 attribute 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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},s={},u=[{value:"#[Type] attribute with the class attribute",id:"type-attribute-with-the-class-attribute",level:2},{value:"#[SourceField] attribute",id:"sourcefield-attribute",level:2},{value:"#[MagicField] attribute",id:"magicfield-attribute",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without attributes)",id:"declaring-fields-dynamically-without-attributes",level:2}],d={toc:u},p="wrapper";function c(e){let{components:t,...n}=e;return(0,i.yg)(p,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In some cases, you cannot or do not want to put an attribute on a domain class."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,i.yg)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with attributes from the view layer"),(0,i.yg)("li",{parentName:"ul"},"etc.")),(0,i.yg)("h2",{id:"type-attribute-with-the-class-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"#[Type]")," attribute with the ",(0,i.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,i.yg)("p",null,"GraphQLite allows you to use a ",(0,i.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute with the ",(0,i.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,i.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("p",null,"In methods with a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute, the first parameter is the ",(0,i.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,i.yg)("h2",{id:"sourcefield-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"#[SourceField]")," attribute"),(0,i.yg)("p",null,"If you don't want to rewrite all ",(0,i.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,i.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,i.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,i.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,i.yg)("h2",{id:"magicfield-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"#[MagicField]")," attribute"),(0,i.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,i.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[MagicField]")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,i.yg)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,i.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,i.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,i.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,i.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" argument.'),(0,i.yg)("pre",null,(0,i.yg)("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#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price", annotations: [new Logged(), new Right("CAN_ACCESS_Price"), new FailWith(null)])]\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,i.yg)("p",null,"Any attributes described in the ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/authentication-authorization"},"Authentication and authorization page"),", or any attribute this is actually a ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/field-middlewares"},'"field middleware"')," can be used in the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]"),' "annotations" argument.'),(0,i.yg)("h2",{id:"declaring-fields-dynamically-without-attributes"},"Declaring fields dynamically (without attributes)"),(0,i.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," attributes at development time.\nIf you need to decide the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," at runtime, you can implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,i.yg)("pre",null,(0,i.yg)("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', 'annotations'=>[new Logged()]]),\n ];\n } else {\n return [];\n }\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/89ed63c8.2ff7c8bc.js b/assets/js/89ed63c8.3a63ee5a.js similarity index 99% rename from assets/js/89ed63c8.2ff7c8bc.js rename to assets/js/89ed63c8.3a63ee5a.js index 220fc0c9f..cc8744788 100644 --- a/assets/js/89ed63c8.2ff7c8bc.js +++ b/assets/js/89ed63c8.3a63ee5a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[573],{19365:(e,n,t)=>{t.d(n,{A:()=>o});var a=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:n,hidden:t,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>I});var a=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function d(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 h(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??d(t);return function(e){const n=(0,s.X)(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 p(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,l.W6)(),i=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.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function m(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=h(e),[o,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(!p({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:i}))),[u,s]=g({queryString:t,groupId:a}),[d,m]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),y=(()=>{const e=u??d;return p({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),m(e)}),[s,m,i]),tabValues:i}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},p=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 r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function N(e){const n=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function I(e){const n=(0,y.A)();return r.createElement(N,(0,a.A)({key:String(n)},e))}},74275:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>g,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],h={toc:d},p="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(p,(0,a.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.yg)("a",{parentName:"li",href:"/docs/4.3/fine-grained-security"},(0,r.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.yg)("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.yg)("br",null),"See ",(0,r.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.yg)("h2",{id:"logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.yg)("p",null,"GraphQLite exposes two annotations (",(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the query ",(0,r.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.3/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.yg)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[573],{19365:(e,n,t)=>{t.d(n,{A:()=>o});var a=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:n,hidden:t,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>I});var a=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function d(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 h(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??d(t);return function(e){const n=(0,s.X)(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 p(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,l.W6)(),i=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.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function m(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=h(e),[o,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(!p({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:i}))),[u,s]=g({queryString:t,groupId:a}),[d,m]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),y=(()=>{const e=u??d;return p({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),m(e)}),[s,m,i]),tabValues:i}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},p=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 r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function N(e){const n=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function I(e){const n=(0,y.A)();return r.createElement(N,(0,a.A)({key:String(n)},e))}},74275:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>g,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],h={toc:d},p="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(p,(0,a.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.yg)("a",{parentName:"li",href:"/docs/4.3/fine-grained-security"},(0,r.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.yg)("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.yg)("br",null),"See ",(0,r.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.yg)("h2",{id:"logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.yg)("p",null,"GraphQLite exposes two annotations (",(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the query ",(0,r.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.3/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.yg)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/8b6bafea.c7a6cf4f.js b/assets/js/8b6bafea.cd594754.js similarity index 99% rename from assets/js/8b6bafea.c7a6cf4f.js rename to assets/js/8b6bafea.cd594754.js index 8563906f5..caafc801c 100644 --- a/assets/js/8b6bafea.c7a6cf4f.js +++ b/assets/js/8b6bafea.cd594754.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2230],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(s.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),s=n(20053),o=n(23104),l=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("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 T(e){const t=f(e);return r.createElement("div",{className:(0,s.A)("tabs-container",y.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,b.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},74128:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),s=(n(67443),n(11470)),o=n(19365);const l={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/5.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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([[2230],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(s.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),s=n(20053),o=n(23104),l=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("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 T(e){const t=f(e);return r.createElement("div",{className:(0,s.A)("tabs-container",y.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,b.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},74128:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),s=(n(67443),n(11470)),o=n(19365);const l={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/5.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.a65e41a7.js b/assets/js/8bf32d27.ffdbfcf5.js similarity index 99% rename from assets/js/8bf32d27.a65e41a7.js rename to assets/js/8bf32d27.ffdbfcf5.js index eeb297b9b..fdfd0e6d7 100644 --- a/assets/js/8bf32d27.a65e41a7.js +++ b/assets/js/8bf32d27.ffdbfcf5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6523],{19365:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(96540),r=a(20053);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.A)(l.tabItem,i),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>x});var n=a(58168),r=a(96540),l=a(20053),i=a(23104),o=a(56347),u=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(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(!y({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,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return y({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),h(e)}),[s,h,l]),tabValues:l}}var f=a(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},y=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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:y,onClick:d},i,{className:(0,l.A)("tabs__item",g.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 T(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",g.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function x(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},12215:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/extend-type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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([[6523],{19365:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(96540),r=a(20053);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.A)(l.tabItem,i),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>x});var n=a(58168),r=a(96540),l=a(20053),i=a(23104),o=a(56347),u=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(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(!y({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,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return y({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),h(e)}),[s,h,l]),tabValues:l}}var f=a(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},y=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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:y,onClick:d},i,{className:(0,l.A)("tabs__item",g.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 T(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",g.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function x(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},12215:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/extend-type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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/8c95fc16.bb8492ea.js b/assets/js/8c95fc16.d1d61a3f.js similarity index 99% rename from assets/js/8c95fc16.bb8492ea.js rename to assets/js/8c95fc16.d1d61a3f.js index 1d86b9d2d..93b915bf0 100644 --- a/assets/js/8c95fc16.bb8492ea.js +++ b/assets/js/8c95fc16.d1d61a3f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9158],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),i=n(56347),s=n(57485),u=n(31682),p=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.W6)(),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.aZ)(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),[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]=y({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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),m=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);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 m=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":i===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 T(e){const t=g(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},98445:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 y(e){let{components:t,...i}=e;return(0,r.yg)(h,(0,a.A)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.yg)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.yg)("p",null,"Read the ",(0,r.yg)("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.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:n(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}y.isMDXComponent=!0},67258:(e,t,n)=>{n.d(t,{A:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9158],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),i=n(56347),s=n(57485),u=n(31682),p=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.W6)(),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.aZ)(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),[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]=y({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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),m=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);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 m=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":i===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 T(e){const t=g(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},98445:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 y(e){let{components:t,...i}=e;return(0,r.yg)(h,(0,a.A)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.yg)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.yg)("p",null,"Read the ",(0,r.yg)("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.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:n(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}y.isMDXComponent=!0},67258:(e,t,n)=>{n.d(t,{A:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/8d81badd.bfee7348.js b/assets/js/8d81badd.fe9f30d2.js similarity index 99% rename from assets/js/8d81badd.bfee7348.js rename to assets/js/8d81badd.fe9f30d2.js index 6868f3c76..ee0bfeaee 100644 --- a/assets/js/8d81badd.bfee7348.js +++ b/assets/js/8d81badd.fe9f30d2.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3701],{15793:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},m,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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([[3701],{15793:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},m,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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/8e97f284.4dfec083.js b/assets/js/8e97f284.e10357e1.js similarity index 98% rename from assets/js/8e97f284.4dfec083.js rename to assets/js/8e97f284.e10357e1.js index a14879017..764111c64 100644 --- a/assets/js/8e97f284.4dfec083.js +++ b/assets/js/8e97f284.e10357e1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5766],{34787:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>s,contentTitle:()=>n,default:()=>h,frontMatter:()=>l,metadata:()=>r,toc:()=>p});var o=t(58168),i=(t(96540),t(15680));t(67443);const l={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},n=void 0,r={unversionedId:"file-uploads",id:"version-8.0.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-8.0.0/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-8.0.0/file-uploads.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"docs",previous:{title:"Automatic persisted queries",permalink:"/docs/automatic-persisted-queries"},next:{title:"Pagination",permalink:"/docs/pagination"}},s={},p=[{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:p},d="wrapper";function h(e){let{components:a,...t}=e;return(0,i.yg)(d,(0,o.A)({},u,t,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,i.yg)("h2",{id:"installation"},"Installation"),(0,i.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,i.yg)("p",null,"You must start by installing this package:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,i.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,i.yg)("p",null,"In order to use this, you must first be sure that the ",(0,i.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,i.yg)("p",null,"Simply add ",(0,i.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,i.yg)("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,i.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,i.yg)("h2",{id:"usage"},"Usage"),(0,i.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,i.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,i.yg)("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,i.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,i.yg)("pre",null,(0,i.yg)("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([[5766],{34787:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>s,contentTitle:()=>n,default:()=>h,frontMatter:()=>l,metadata:()=>r,toc:()=>p});var o=t(58168),i=(t(96540),t(15680));t(67443);const l={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},n=void 0,r={unversionedId:"file-uploads",id:"version-8.0.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-8.0.0/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-8.0.0/file-uploads.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads"},sidebar:"docs",previous:{title:"Automatic persisted queries",permalink:"/docs/automatic-persisted-queries"},next:{title:"Pagination",permalink:"/docs/pagination"}},s={},p=[{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:p},d="wrapper";function h(e){let{components:a,...t}=e;return(0,i.yg)(d,(0,o.A)({},u,t,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,i.yg)("h2",{id:"installation"},"Installation"),(0,i.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,i.yg)("p",null,"You must start by installing this package:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,i.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,i.yg)("p",null,"In order to use this, you must first be sure that the ",(0,i.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,i.yg)("p",null,"Simply add ",(0,i.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,i.yg)("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,i.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,i.yg)("h2",{id:"usage"},"Usage"),(0,i.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,i.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,i.yg)("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,i.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,i.yg)("pre",null,(0,i.yg)("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/8f7abfe1.0fd15954.js b/assets/js/8f7abfe1.e7a52f5f.js similarity index 99% rename from assets/js/8f7abfe1.0fd15954.js rename to assets/js/8f7abfe1.e7a52f5f.js index 0a8a7bfa9..ab3026f6e 100644 --- a/assets/js/8f7abfe1.0fd15954.js +++ b/assets/js/8f7abfe1.e7a52f5f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2592],{21703:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>i,metadata:()=>o,toc:()=>p});var a=t(58168),r=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:n,...i}=e;return(0,r.yg)(y,(0,a.A)({},u,i,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:t(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}h.isMDXComponent=!0},67258:(e,n,t)=>{t.d(n,{A:()=>a});const a=t.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2592],{21703:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>i,metadata:()=>o,toc:()=>p});var a=t(58168),r=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:n,...i}=e;return(0,r.yg)(y,(0,a.A)({},u,i,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:t(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}h.isMDXComponent=!0},67258:(e,n,t)=>{t.d(n,{A:()=>a});const a=t.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/8f7fa040.2b316d49.js b/assets/js/8f7fa040.88306093.js similarity index 99% rename from assets/js/8f7fa040.2b316d49.js rename to assets/js/8f7fa040.88306093.js index 8b8b0227c..496c95f0a 100644 --- a/assets/js/8f7fa040.2b316d49.js +++ b/assets/js/8f7fa040.88306093.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1505],{23511:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>r,metadata:()=>l,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:n,...t}=e;return(0,i.yg)(c,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,i.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,i.yg)("p",null,"Let's assume you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," method in the product because the name needs to be translated in the correct language. You have a ",(0,i.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Using ",(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Let's break this sample:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")),(0,i.yg)("p",null,"With the ",(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,i.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,i.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,i.yg)("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.yg)("p",null,'Using the "',(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,i.yg)("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([[1505],{23511:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>r,metadata:()=>l,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:n,...t}=e;return(0,i.yg)(c,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,i.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,i.yg)("p",null,"Let's assume you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," method in the product because the name needs to be translated in the correct language. You have a ",(0,i.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Using ",(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Let's break this sample:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")),(0,i.yg)("p",null,"With the ",(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,i.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,i.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,i.yg)("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.yg)("p",null,'Using the "',(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,i.yg)("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.6f6d22dc.js b/assets/js/8f951ce3.5a4dc1f3.js similarity index 99% rename from assets/js/8f951ce3.6f6d22dc.js rename to assets/js/8f951ce3.5a4dc1f3.js index 124a204d7..5cc6a0e75 100644 --- a/assets/js/8f951ce3.6f6d22dc.js +++ b/assets/js/8f951ce3.5a4dc1f3.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9439],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(s.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),s=n(20053),o=n(23104),l=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("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 T(e){const t=f(e);return r.createElement("div",{className:(0,s.A)("tabs-container",y.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,b.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},88067:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),s=(n(67443),n(11470)),o=n(19365);const l={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.2/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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([[9439],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(s.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),s=n(20053),o=n(23104),l=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("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 T(e){const t=f(e);return r.createElement("div",{className:(0,s.A)("tabs-container",y.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,b.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},88067:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),s=(n(67443),n(11470)),o=n(19365);const l={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.2/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.9b309dd8.js b/assets/js/8f967659.d7936e3d.js similarity index 98% rename from assets/js/8f967659.9b309dd8.js rename to assets/js/8f967659.d7936e3d.js index 09cf9ed3d..945f80b21 100644 --- a/assets/js/8f967659.9b309dd8.js +++ b/assets/js/8f967659.d7936e3d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[109],{28185:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental"),"\nand their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"li"},"composer.json"),", target a major version:",(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"li"},"composer.json"),", target a minor version:",(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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([[109],{28185:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental"),"\nand their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"li"},"composer.json"),", target a major version:",(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"li"},"composer.json"),", target a minor version:",(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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.83f9d52f.js b/assets/js/9000b231.13a2c4ab.js similarity index 98% rename from assets/js/9000b231.83f9d52f.js rename to assets/js/9000b231.13a2c4ab.js index af31e682f..5164e3d48 100644 --- a/assets/js/9000b231.83f9d52f.js +++ b/assets/js/9000b231.13a2c4ab.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2032],{1727:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>p});var n=t(58168),r=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"migrating",title:"Release notes",sidebar_label:"Release notes",original_id:"migrating"}},s={},p=[{value:"First stable release of GraphQLite",id:"first-stable-release-of-graphqlite",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},g="wrapper";function u(e){let{components:a,...t}=e;return(0,r.yg)(g,(0,n.A)({},d,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"first-stable-release-of-graphqlite"},"First stable release of GraphQLite"),(0,r.yg)("p",null,"GraphQLite is PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony and Laravel bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, extendable types and more!")),(0,r.yg)("p",null,"After several months of work, we are very happy to announce the availability of GraphQLite v3.0."),(0,r.yg)("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.yg)("p",null,(0,r.yg)("a",{parentName:"p",href:"https://graphqlite.thecodingmachine.io"},"Check out the documentation")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go \ud83c\udf89! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2032],{1727:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>p});var n=t(58168),r=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"migrating",title:"Release notes",sidebar_label:"Release notes",original_id:"migrating"}},s={},p=[{value:"First stable release of GraphQLite",id:"first-stable-release-of-graphqlite",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},g="wrapper";function u(e){let{components:a,...t}=e;return(0,r.yg)(g,(0,n.A)({},d,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"first-stable-release-of-graphqlite"},"First stable release of GraphQLite"),(0,r.yg)("p",null,"GraphQLite is PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony and Laravel bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, extendable types and more!")),(0,r.yg)("p",null,"After several months of work, we are very happy to announce the availability of GraphQLite v3.0."),(0,r.yg)("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.yg)("p",null,(0,r.yg)("a",{parentName:"p",href:"https://graphqlite.thecodingmachine.io"},"Check out the documentation")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go \ud83c\udf89! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9073923c.ef617e12.js b/assets/js/9073923c.de36f167.js similarity index 98% rename from assets/js/9073923c.ef617e12.js rename to assets/js/9073923c.de36f167.js index bc0f0498c..7e38e5234 100644 --- a/assets/js/9073923c.ef617e12.js +++ b/assets/js/9073923c.de36f167.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4017],{23328:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>d,frontMatter:()=>s,metadata:()=>i,toc:()=>l});var n=a(58168),p=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:t,...a}=e;return(0,p.yg)(y,(0,n.A)({},r,a,{components:t,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.yg)("p",null,"GraphQL comes with an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID!")\n */\n')),(0,p.yg)("h2",{id:"usage"},"Usage"),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.yg)("p",null,"You can use the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Query")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Field")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@SourceField"))),(0,p.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.yg)("p",null,"In order to create a custom output type, you need to:"),(0,p.yg)("ol",null,(0,p.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,p.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.yg)("p",null,"You'll find more details on the ",(0,p.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,p.yg)("hr",null),(0,p.yg)("p",null,"In order to find existing types, the schema is using ",(0,p.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,p.yg)("p",null,"Any class extending ",(0,p.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.yg)("p",null,"The easiest way is to use a ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.yg)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4017],{23328:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>d,frontMatter:()=>s,metadata:()=>i,toc:()=>l});var n=a(58168),p=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:t,...a}=e;return(0,p.yg)(y,(0,n.A)({},r,a,{components:t,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.yg)("p",null,"GraphQL comes with an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID!")\n */\n')),(0,p.yg)("h2",{id:"usage"},"Usage"),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.yg)("p",null,"You can use the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Query")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Field")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@SourceField"))),(0,p.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.yg)("p",null,"In order to create a custom output type, you need to:"),(0,p.yg)("ol",null,(0,p.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,p.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.yg)("p",null,"You'll find more details on the ",(0,p.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-system/object-types/"},"Webonyx documentation"),"."),(0,p.yg)("hr",null),(0,p.yg)("p",null,"In order to find existing types, the schema is using ",(0,p.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,p.yg)("p",null,"Any class extending ",(0,p.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.yg)("p",null,"The easiest way is to use a ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.yg)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/90e0b7fd.24725f2e.js b/assets/js/90e0b7fd.5581a186.js similarity index 99% rename from assets/js/90e0b7fd.24725f2e.js rename to assets/js/90e0b7fd.5581a186.js index b339898c4..f5f35c48e 100644 --- a/assets/js/90e0b7fd.24725f2e.js +++ b/assets/js/90e0b7fd.5581a186.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5856],{28565:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"docs",previous:{title:"Symfony bundle",permalink:"/docs/6.1/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/6.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}],g={toc:s},h="wrapper";function u(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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([[5856],{28565:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"laravel-package",title:"Getting started with Laravel",sidebar_label:"Laravel package"},sidebar:"docs",previous:{title:"Symfony bundle",permalink:"/docs/6.1/symfony-bundle"},next:{title:"Universal service providers",permalink:"/docs/6.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}],g={toc:s},h="wrapper";function u(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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/91e22cb6.8a82af14.js b/assets/js/91e22cb6.f499f373.js similarity index 99% rename from assets/js/91e22cb6.8a82af14.js rename to assets/js/91e22cb6.f499f373.js index ba3966d9e..abd5ed394 100644 --- a/assets/js/91e22cb6.8a82af14.js +++ b/assets/js/91e22cb6.f499f373.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9917],{43698:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>o,contentTitle:()=>l,default:()=>h,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var n=a(58168),r=(a(96540),a(15680));a(67443);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},l=void 0,s={unversionedId:"queries",id:"version-8.0.0/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-8.0.0/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/queries.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},o={},p=[{value:"Simple query",id:"simple-query",level:2},{value:"About attributes",id:"about-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}],u={toc:p},y="wrapper";function h(e){let{components:t,...i}=e;return(0,r.yg)(y,(0,n.A)({},u,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]")," attribute. For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-attributes"},"About attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on attributes."),(0,r.yg)("p",null,"It supports the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),'), the "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),") was dropped."),(0,r.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:a(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute is used to define the GraphQL fields. This attribute must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL attributes are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," attributes and for most project, this is the fastest and easiest route."),(0,r.yg)("p",null,"If you feel that GraphQL attributes 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.")))}h.isMDXComponent=!0},67258:(e,t,a)=>{a.d(t,{A:()=>n});const n=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9917],{43698:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>o,contentTitle:()=>l,default:()=>h,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var n=a(58168),r=(a(96540),a(15680));a(67443);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},l=void 0,s={unversionedId:"queries",id:"version-8.0.0/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-8.0.0/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/queries.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},o={},p=[{value:"Simple query",id:"simple-query",level:2},{value:"About attributes",id:"about-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}],u={toc:p},y="wrapper";function h(e){let{components:t,...i}=e;return(0,r.yg)(y,(0,n.A)({},u,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]")," attribute. For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-attributes"},"About attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on attributes."),(0,r.yg)("p",null,"It supports the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),'), the "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),") was dropped."),(0,r.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:a(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute is used to define the GraphQL fields. This attribute must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL attributes are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," attributes and for most project, this is the fastest and easiest route."),(0,r.yg)("p",null,"If you feel that GraphQL attributes 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.")))}h.isMDXComponent=!0},67258:(e,t,a)=>{a.d(t,{A:()=>n});const n=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/9206a32f.bf2cd8fc.js b/assets/js/9206a32f.1c791804.js similarity index 99% rename from assets/js/9206a32f.bf2cd8fc.js rename to assets/js/9206a32f.1c791804.js index 331e04fe5..a35298963 100644 --- a/assets/js/9206a32f.bf2cd8fc.js +++ b/assets/js/9206a32f.1c791804.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7696],{46284:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/6.0/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/6.0/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7696],{46284:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/6.0/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/6.0/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9279cea7.1e1e0a39.js b/assets/js/9279cea7.bfbca50a.js similarity index 99% rename from assets/js/9279cea7.1e1e0a39.js rename to assets/js/9279cea7.bfbca50a.js index 779960285..f40d2ce27 100644 --- a/assets/js/9279cea7.1e1e0a39.js +++ b/assets/js/9279cea7.bfbca50a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9262],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),i=a(89466);function y(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??y(a);return function(e){const t=(0,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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(!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}),[y,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=s??y;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:y}=(0,o.a_)(),c=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(y(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":c(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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:c},o,{className:(0,p.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},31950:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>y});var n=a(58168),r=(a(96540),a(15680)),p=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],c={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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([[9262],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),i=a(89466);function y(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??y(a);return function(e){const t=(0,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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(!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}),[y,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=s??y;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:y}=(0,o.a_)(),c=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(y(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":c(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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:c},o,{className:(0,p.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},31950:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>y});var n=a(58168),r=(a(96540),a(15680)),p=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],c={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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.dc4d6da3.js b/assets/js/947f2c39.5b80a366.js similarity index 99% rename from assets/js/947f2c39.dc4d6da3.js rename to assets/js/947f2c39.5b80a366.js index e6ea9a5df..908e8303d 100644 --- a/assets/js/947f2c39.dc4d6da3.js +++ b/assets/js/947f2c39.5b80a366.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7846],{23693:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>y,toc:()=>l});var n=a(58168),p=(a(96540),a(15680));a(67443);const o={id:"custom-types",title:"Custom types",sidebar_label:"Custom types",original_id:"custom-types"},r=void 0,y={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},i={},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},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],s={toc:l},u="wrapper";function c(e){let{components:t,...a}=e;return(0,p.yg)(u,(0,n.A)({},s,a,{components:t,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.yg)("p",null,"GraphQL comes with an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')),(0,p.yg)("h2",{id:"usage"},"Usage"),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.yg)("p",null,"You can use the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Query")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Field")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,p.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.yg)("p",null,"In order to create a custom output type, you need to:"),(0,p.yg)("ol",null,(0,p.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,p.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.yg)("p",null,"You'll find more details on the ",(0,p.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,p.yg)("hr",null),(0,p.yg)("p",null,"In order to find existing types, the schema is using ",(0,p.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,p.yg)("p",null,"Any class extending ",(0,p.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.yg)("p",null,"The easiest way is to use a ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.yg)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."),(0,p.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,p.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,p.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,p.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},"create a ",(0,p.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,p.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,p.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,p.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,p.yg)("p",null,"RootTypeMapper are organized ",(0,p.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,p.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,p.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,p.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,p.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,p.yg)("p",null,"You can register your own root mapper factories using the ",(0,p.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,p.yg)("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([[7846],{23693:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>y,toc:()=>l});var n=a(58168),p=(a(96540),a(15680));a(67443);const o={id:"custom-types",title:"Custom types",sidebar_label:"Custom types",original_id:"custom-types"},r=void 0,y={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},i={},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},{value:"Registering a custom scalar type (advanced)",id:"registering-a-custom-scalar-type-advanced",level:2}],s={toc:l},u="wrapper";function c(e){let{components:t,...a}=e;return(0,p.yg)(u,(0,n.A)({},s,a,{components:t,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,p.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,p.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,p.yg)("p",null,"GraphQL comes with an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,p.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')),(0,p.yg)("h2",{id:"usage"},"Usage"),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,p.yg)("p",null,"You can use the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Query")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@Field")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,p.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,p.yg)("p",null,"In order to create a custom output type, you need to:"),(0,p.yg)("ol",null,(0,p.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,p.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,p.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,p.yg)("p",null,"You'll find more details on the ",(0,p.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,p.yg)("hr",null),(0,p.yg)("p",null,"In order to find existing types, the schema is using ",(0,p.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,p.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,p.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,p.yg)("p",null,"Any class extending ",(0,p.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,p.yg)("p",null,"The easiest way is to use a ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". This class is used to register custom output types."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper")," instance MUST be registered in your container and linked to a ",(0,p.yg)("inlineCode",{parentName:"p"},"CompositeTypeMapper"),"\nthat will aggregate all the type mappers of the application."),(0,p.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,p.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,p.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,p.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},"create a ",(0,p.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,p.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,p.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,p.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,p.yg)("p",null,"RootTypeMapper are organized ",(0,p.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,p.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,p.yg)("p",null,"For instance:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,p.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,p.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,p.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,p.yg)("p",null,"You can register your own root mapper factories using the ",(0,p.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,p.yg)("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/94ecc552.4ea01d21.js b/assets/js/94ecc552.3b2f4d51.js similarity index 99% rename from assets/js/94ecc552.4ea01d21.js rename to assets/js/94ecc552.3b2f4d51.js index e8c40fc24..b4ac3ef41 100644 --- a/assets/js/94ecc552.4ea01d21.js +++ b/assets/js/94ecc552.3b2f4d51.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2197],{80065:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>y,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(58168),i=(a(96540),a(15680));a(67443);const o={id:"validation",title:"Validation",sidebar_label:"User input validation"},r=void 0,l={unversionedId:"validation",id:"version-8.0.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-8.0.0/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/validation.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},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 / subscription / factory ...",id:"using-the-validator-directly-on-a-query--mutation--subscription--factory-",level:3},{value:"Custom InputType Validation",id:"custom-inputtype-validation",level:2}],p={toc:d},u="wrapper";function y(e){let{components:t,...a}=e;return(0,i.yg)(u,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.yg)("pre",{parentName:"li"},(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.yg)("p",null,"Usually, when you use the Symfony validator component, you put attributes in your entities and you validate those entities\nusing the ",(0,i.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.yg)("pre",null,(0,i.yg)("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 }\n }\n ]\n}\n')),(0,i.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--subscription--factory-"},"Using the validator directly on a query / mutation / subscription / factory ..."),(0,i.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,i.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.yg)("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.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Assertion]")," attribute to validate directly the user input."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\GraphQLite\\Validator\\Annotations\\Assertion;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\n#[Query]\n#[Assertion(for: "email", constraint: new Assert\\Email())]\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,i.yg)("p",null,'Notice that the "constraint" parameter contains an attribute (it is an attribute wrapped in an attribute).'),(0,i.yg)("p",null,"You can also pass an array to the ",(0,i.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Assertion(for: "email", constraint: [new Assert\\NotBlack(), new Assert\\Email()])]\n')),(0,i.yg)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.yg)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.yg)("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.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("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.yg)("p",null,"To get started with validation on input types defined by an ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute, you'll first need to register your validator with the ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"$factory = new SchemaFactory($cache, $this->container);\n$factory->addNamespace('App');\n// Register your validator\n$factory->setInputTypeValidator($this->container->get('your_validator'));\n$factory->createSchema();\n")),(0,i.yg)("p",null,"Your input type validator must implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.yg)("inlineCode",{parentName:"p"},"validate")," method. For example, you might use Symfony's attribute 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.yg)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.yg)("p",null,"You'll notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.yg)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.yg)("p",null,"Also available is the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.yg)("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."))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2197],{80065:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>y,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=a(58168),i=(a(96540),a(15680));a(67443);const o={id:"validation",title:"Validation",sidebar_label:"User input validation"},r=void 0,l={unversionedId:"validation",id:"version-8.0.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-8.0.0/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/validation.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},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 / subscription / factory ...",id:"using-the-validator-directly-on-a-query--mutation--subscription--factory-",level:3},{value:"Custom InputType Validation",id:"custom-inputtype-validation",level:2}],p={toc:d},u="wrapper";function y(e){let{components:t,...a}=e;return(0,i.yg)(u,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.yg)("pre",{parentName:"li"},(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.yg)("p",null,"Usually, when you use the Symfony validator component, you put attributes in your entities and you validate those entities\nusing the ",(0,i.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.yg)("pre",null,(0,i.yg)("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 }\n }\n ]\n}\n')),(0,i.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--subscription--factory-"},"Using the validator directly on a query / mutation / subscription / factory ..."),(0,i.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,i.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.yg)("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.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Assertion]")," attribute to validate directly the user input."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'use Symfony\\Component\\Validator\\Constraints as Assert;\nuse TheCodingMachine\\GraphQLite\\Validator\\Annotations\\Assertion;\nuse TheCodingMachine\\GraphQLite\\Annotations\\Query;\n\n#[Query]\n#[Assertion(for: "email", constraint: new Assert\\Email())]\npublic function findByMail(string $email): User\n{\n // ...\n}\n')),(0,i.yg)("p",null,'Notice that the "constraint" parameter contains an attribute (it is an attribute wrapped in an attribute).'),(0,i.yg)("p",null,"You can also pass an array to the ",(0,i.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Assertion(for: "email", constraint: [new Assert\\NotBlack(), new Assert\\Email()])]\n')),(0,i.yg)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.yg)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.yg)("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.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("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.yg)("p",null,"To get started with validation on input types defined by an ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute, you'll first need to register your validator with the ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"$factory = new SchemaFactory($cache, $this->container);\n$factory->addNamespace('App');\n// Register your validator\n$factory->setInputTypeValidator($this->container->get('your_validator'));\n$factory->createSchema();\n")),(0,i.yg)("p",null,"Your input type validator must implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.yg)("inlineCode",{parentName:"p"},"validate")," method. For example, you might use Symfony's attribute 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.yg)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.yg)("p",null,"You'll notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.yg)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.yg)("p",null,"Also available is the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.yg)("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."))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/950394a4.c594d384.js b/assets/js/950394a4.ad4896b0.js similarity index 99% rename from assets/js/950394a4.c594d384.js rename to assets/js/950394a4.ad4896b0.js index 31b44d208..fabb0f3c8 100644 --- a/assets/js/950394a4.c594d384.js +++ b/assets/js/950394a4.ad4896b0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8194],{19365:(e,n,t)=>{t.d(n,{A:()=>o});var a=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:n,hidden:t,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>I});var a=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),s=t(57485),u=t(31682),c=t(89466);function p(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??p(t);return function(e){const n=(0,u.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,l.W6)(),i=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.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function m(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=d(e),[o,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:i}))),[s,u]=g({queryString:t,groupId:a}),[p,m]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),m(e)}),[u,m,i]),tabValues:i}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=u[t].value;a!==l&&(p(n),s(a))},h=e=>{let n=null;switch(e.key){case"Enter":d(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 r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:h,onClick:d},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function N(e){const n=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function I(e){const n=(0,y.A)();return r.createElement(N,(0,a.A)({key:String(n)},e))}},28909:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);const l={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},s=void 0,u={unversionedId:"authentication-authorization",id:"version-7.0.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",source:"@site/versioned_docs/version-7.0.0/authentication-authorization.mdx",sourceDirName:".",slug:"/authentication-authorization",permalink:"/docs/7.0.0/authentication-authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/authentication-authorization.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"docs",previous:{title:"User input validation",permalink:"/docs/7.0.0/validation"},next:{title:"Fine grained security",permalink:"/docs/7.0.0/fine-grained-security"}},c={},p=[{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 / subscriptions",id:"hiding-fields--queries--mutations--subscriptions",level:2}],d={toc:p},h="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(h,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some\nqueries/mutations/subscriptions or fields reserved to some users."),(0,r.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to\nresources:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.yg)("a",{parentName:"li",href:"/docs/7.0.0/fine-grained-security"},(0,r.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.yg)("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.yg)("br",null),"See ",(0,r.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.yg)("h2",{id:"logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.yg)("p",null,"GraphQLite exposes two annotations (",(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the query ",(0,r.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/subscription/field, an error is raised and the query fails."),(0,r.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.yg)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation/subscription\nthey have no access to, you can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/7.0.0/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.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation."),(0,r.yg)("h2",{id:"hiding-fields--queries--mutations--subscriptions"},"Hiding fields / queries / mutations / subscriptions"),(0,r.yg)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/subscriptions/types available.\nSome will be available to him and some won't."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation. Beware of ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/annotations-reference"},"it's limitations"),"."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optional from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8194],{19365:(e,n,t)=>{t.d(n,{A:()=>o});var a=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:n,hidden:t,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>I});var a=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),s=t(57485),u=t(31682),c=t(89466);function p(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??p(t);return function(e){const n=(0,u.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,l.W6)(),i=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.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function m(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=d(e),[o,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:i}))),[s,u]=g({queryString:t,groupId:a}),[p,m]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),m(e)}),[u,m,i]),tabValues:i}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=u[t].value;a!==l&&(p(n),s(a))},h=e=>{let n=null;switch(e.key){case"Enter":d(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 r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:h,onClick:d},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function N(e){const n=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function I(e){const n=(0,y.A)();return r.createElement(N,(0,a.A)({key:String(n)},e))}},28909:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);const l={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},s=void 0,u={unversionedId:"authentication-authorization",id:"version-7.0.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",source:"@site/versioned_docs/version-7.0.0/authentication-authorization.mdx",sourceDirName:".",slug:"/authentication-authorization",permalink:"/docs/7.0.0/authentication-authorization",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/authentication-authorization.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"docs",previous:{title:"User input validation",permalink:"/docs/7.0.0/validation"},next:{title:"Fine grained security",permalink:"/docs/7.0.0/fine-grained-security"}},c={},p=[{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 / subscriptions",id:"hiding-fields--queries--mutations--subscriptions",level:2}],d={toc:p},h="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(h,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some\nqueries/mutations/subscriptions or fields reserved to some users."),(0,r.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to\nresources:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.yg)("a",{parentName:"li",href:"/docs/7.0.0/fine-grained-security"},(0,r.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.yg)("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.yg)("br",null),"See ",(0,r.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.yg)("h2",{id:"logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.yg)("p",null,"GraphQLite exposes two annotations (",(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the query ",(0,r.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/subscription/field, an error is raised and the query fails."),(0,r.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.yg)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation/subscription\nthey have no access to, you can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/7.0.0/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.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation."),(0,r.yg)("h2",{id:"hiding-fields--queries--mutations--subscriptions"},"Hiding fields / queries / mutations / subscriptions"),(0,r.yg)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/subscriptions/types available.\nSome will be available to him and some won't."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation. Beware of ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/annotations-reference"},"it's limitations"),"."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optional from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/95073452.e4451793.js b/assets/js/95073452.bb48107c.js similarity index 98% rename from assets/js/95073452.e4451793.js rename to assets/js/95073452.bb48107c.js index 89fdcc338..53bf97ef6 100644 --- a/assets/js/95073452.e4451793.js +++ b/assets/js/95073452.bb48107c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5962],{78275:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>p,frontMatter:()=>o,metadata:()=>s,toc:()=>u});var n=i(58168),a=(i(96540),i(15680));i(67443);const o={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},r=void 0,s={unversionedId:"autowiring",id:"version-8.0.0/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-8.0.0/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/autowiring.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},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.yg)(d,(0,n.A)({},c,i,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,a.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,a.yg)("p",null,"Most of the time, your ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute 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.yg)("h2",{id:"sample"},"Sample"),(0,a.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,a.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,a.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,a.yg)("h2",{id:"best-practices"},"Best practices"),(0,a.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,a.yg)("pre",null,(0,a.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,a.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,a.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,a.yg)("pre",null,(0,a.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,a.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,a.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,a.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n')),(0,a.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,a.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,a.yg)("ul",null,(0,a.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,a.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,a.yg)("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.yg)("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([[5962],{78275:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>p,frontMatter:()=>o,metadata:()=>s,toc:()=>u});var n=i(58168),a=(i(96540),i(15680));i(67443);const o={id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services"},r=void 0,s={unversionedId:"autowiring",id:"version-8.0.0/autowiring",title:"Autowiring services",description:"GraphQLite can automatically inject services in your fields/queries/mutations signatures.",source:"@site/versioned_docs/version-8.0.0/autowiring.mdx",sourceDirName:".",slug:"/autowiring",permalink:"/docs/autowiring",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/autowiring.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},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.yg)(d,(0,n.A)({},c,i,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,a.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,a.yg)("p",null,"Most of the time, your ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute 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.yg)("h2",{id:"sample"},"Sample"),(0,a.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,a.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,a.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,a.yg)("h2",{id:"best-practices"},"Best practices"),(0,a.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,a.yg)("pre",null,(0,a.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,a.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,a.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,a.yg)("pre",null,(0,a.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,a.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,a.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,a.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n')),(0,a.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,a.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,a.yg)("ul",null,(0,a.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,a.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,a.yg)("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.yg)("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/95576100.d95ae89b.js b/assets/js/95576100.0f56eb6d.js similarity index 99% rename from assets/js/95576100.d95ae89b.js rename to assets/js/95576100.0f56eb6d.js index e7bf2c782..7993a9578 100644 --- a/assets/js/95576100.d95ae89b.js +++ b/assets/js/95576100.0f56eb6d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1898],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),g(e)}),[u,g,i]),tabValues:i}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function T(e){const t=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},52236:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),i=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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,...a}=e;return(0,r.yg)(h,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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([[1898],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),g(e)}),[u,g,i]),tabValues:i}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function T(e){const t=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},52236:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),i=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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,...a}=e;return(0,r.yg)(h,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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.1e08f94f.js b/assets/js/9664ee55.c3f50066.js similarity index 99% rename from assets/js/9664ee55.1e08f94f.js rename to assets/js/9664ee55.c3f50066.js index 58eef055f..fca0cc48a 100644 --- a/assets/js/9664ee55.1e08f94f.js +++ b/assets/js/9664ee55.c3f50066.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7544],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var r=a(96540),t=a(20053);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,t.A)(o.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>$});var r=a(58168),t=a(96540),o=a(20053),i=a(23104),l=a(56347),s=a(57485),c=a(31682),p=a(89466);function u(e){return function(e){return t.Children.map(e,(e=>{if(!e||(0,t.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:a,attributes:r,default:t}}=e;return{value:n,label:a,attributes:r,default:t}}))}function d(e){const{values:n,children:a}=e;return(0,t.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function h(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:a}=e;const r=(0,l.W6)(),o=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(o),(0,t.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 y(e){const{defaultValue:n,queryString:a=!1,groupId:r}=e,o=d(e),[i,l]=(0,t.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,c]=m({queryString:a,groupId:r}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,p.Dv)(a);return[r,(0,t.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:r}),g=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,t.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:i,selectValue:(0,t.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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),d=e=>{const n=e.currentTarget,a=p.indexOf(n),r=c[a].value;r!==l&&(u(n),s(r))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;n=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;n=p[a]??p[p.length-1];break}}n?.focus()};return t.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return t.createElement("li",(0,r.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":l===n})}),a??n)})))}function w(e){let{lazy:n,children:a,selectedValue:r}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,t.cloneElement)(e,{className:"margin-top--md"}):null}return t.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,t.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=y(e);return t.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},t.createElement(b,(0,r.A)({},e,n)),t.createElement(w,(0,r.A)({},e,n)))}function $(e){const n=(0,g.A)();return t.createElement(v,(0,r.A)({key:String(n)},e))}},14396:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var r=a(58168),t=(a(96540),a(15680)),o=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:n,...a}=e;return(0,t.yg)(h,(0,r.A)({},d,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,t.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("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([[7544],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var r=a(96540),t=a(20053);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,t.A)(o.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>$});var r=a(58168),t=a(96540),o=a(20053),i=a(23104),l=a(56347),s=a(57485),c=a(31682),p=a(89466);function u(e){return function(e){return t.Children.map(e,(e=>{if(!e||(0,t.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:a,attributes:r,default:t}}=e;return{value:n,label:a,attributes:r,default:t}}))}function d(e){const{values:n,children:a}=e;return(0,t.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function h(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:a}=e;const r=(0,l.W6)(),o=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(o),(0,t.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 y(e){const{defaultValue:n,queryString:a=!1,groupId:r}=e,o=d(e),[i,l]=(0,t.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,c]=m({queryString:a,groupId:r}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,p.Dv)(a);return[r,(0,t.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:r}),g=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,t.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:i,selectValue:(0,t.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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),d=e=>{const n=e.currentTarget,a=p.indexOf(n),r=c[a].value;r!==l&&(u(n),s(r))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;n=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;n=p[a]??p[p.length-1];break}}n?.focus()};return t.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return t.createElement("li",(0,r.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":l===n})}),a??n)})))}function w(e){let{lazy:n,children:a,selectedValue:r}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,t.cloneElement)(e,{className:"margin-top--md"}):null}return t.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,t.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=y(e);return t.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},t.createElement(b,(0,r.A)({},e,n)),t.createElement(w,(0,r.A)({},e,n)))}function $(e){const n=(0,g.A)();return t.createElement(v,(0,r.A)({key:String(n)},e))}},14396:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var r=a(58168),t=(a(96540),a(15680)),o=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:n,...a}=e;return(0,t.yg)(h,(0,r.A)({},d,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,t.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("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.b1d01353.js b/assets/js/96877411.577742e6.js similarity index 99% rename from assets/js/96877411.b1d01353.js rename to assets/js/96877411.577742e6.js index 301b4a638..4b8fa4ec5 100644 --- a/assets/js/96877411.b1d01353.js +++ b/assets/js/96877411.577742e6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5526],{80863:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},l=void 0,o={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},s={},p=[],d={toc:p},c="wrapper";function u(e){let{components:t,...n}=e;return(0,i.yg)(c,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute to add additional fields to a type that is already declared."),(0,i.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,i.yg)("p",null,"Let's assume you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,i.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Using ",(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]"),", you can add an additional ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Let's break this sample:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,i.yg)("p",null,"With the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,i.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]"),' attribute is used to add the "name" field to the ',(0,i.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,i.yg)("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.yg)("p",null,'Using the "',(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,i.yg)("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([[5526],{80863:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>u,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"extend-type",title:"Extending a type",sidebar_label:"Extending a type"},l=void 0,o={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},s={},p=[],d={toc:p},c="wrapper";function u(e){let{components:t,...n}=e;return(0,i.yg)(c,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute to add additional fields to a type that is already declared."),(0,i.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,i.yg)("p",null,"Let's assume you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,i.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Using ",(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]"),", you can add an additional ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Let's break this sample:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n")),(0,i.yg)("p",null,"With the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,i.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]"),' attribute is used to add the "name" field to the ',(0,i.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,i.yg)("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.yg)("p",null,'Using the "',(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,i.yg)("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/96fc29fc.9890d336.js b/assets/js/96fc29fc.fee6f6db.js similarity index 99% rename from assets/js/96fc29fc.9890d336.js rename to assets/js/96fc29fc.fee6f6db.js index 722e2b3e7..7263df764 100644 --- a/assets/js/96fc29fc.9890d336.js +++ b/assets/js/96fc29fc.fee6f6db.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6369],{83269:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>l});var a=n(58168),i=(n(96540),n(15680));n(67443);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-8.0.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-8.0.0/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-8.0.0/doctrine-annotations-attributes.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:"Attributes reference",permalink:"/docs/annotations-reference"}},u={},l=[{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:l},p="wrapper";function d(t){let{components:e,...n}=t;return(0,i.yg)(p,(0,a.A)({},c,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.yg)("div",{class:"alert alert--danger"},(0,i.yg)("strong",null,"Unsupported!")," Doctrine annotations are replaced in favor of native PHP 8 attributes."),(0,i.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.yg)("p",null,"The same code can be written this way:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.yg)("p",null,"They support the same attributes too."),(0,i.yg)("p",null,"A few notable differences:"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("p",null,"Let's take an example with the ",(0,i.yg)("a",{parentName:"p",href:"/docs/autowiring"},(0,i.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")),(0,i.yg)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,i.yg)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/rectorphp/rector"},"Rector library"),". To do so, you'll want to use the following rector configuration:"),(0,i.yg)("pre",null,(0,i.yg)("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([[6369],{83269:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>l});var a=n(58168),i=(n(96540),n(15680));n(67443);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-8.0.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-8.0.0/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-8.0.0/doctrine-annotations-attributes.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:"Attributes reference",permalink:"/docs/annotations-reference"}},u={},l=[{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:l},p="wrapper";function d(t){let{components:e,...n}=t;return(0,i.yg)(p,(0,a.A)({},c,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.yg)("div",{class:"alert alert--danger"},(0,i.yg)("strong",null,"Unsupported!")," Doctrine annotations are replaced in favor of native PHP 8 attributes."),(0,i.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.yg)("p",null,"The same code can be written this way:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.yg)("p",null,"They support the same attributes too."),(0,i.yg)("p",null,"A few notable differences:"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("p",null,"Let's take an example with the ",(0,i.yg)("a",{parentName:"p",href:"/docs/autowiring"},(0,i.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")),(0,i.yg)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,i.yg)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/rectorphp/rector"},"Rector library"),". To do so, you'll want to use the following rector configuration:"),(0,i.yg)("pre",null,(0,i.yg)("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/9749ab4a.ae341e96.js b/assets/js/9749ab4a.4554c7eb.js similarity index 99% rename from assets/js/9749ab4a.ae341e96.js rename to assets/js/9749ab4a.4554c7eb.js index 40c774dda..ea22919c1 100644 --- a/assets/js/9749ab4a.ae341e96.js +++ b/assets/js/9749ab4a.4554c7eb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7110],{13401:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>d,contentTitle:()=>r,default:()=>u,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var t=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function u(e){let{components:a,...n}=e;return(0,i.yg)(g,(0,t.A)({},s,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"500"},"5.0.0"),(0,i.yg)("h4",{id:"dependencies"},"Dependencies:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.yg)("h2",{id:"430"},"4.3.0"),(0,i.yg)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The method ",(0,i.yg)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.yg)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.yg)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.yg)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h4",{id:"new-features"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/input-types#input-annotation"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h4",{id:"new-features-1"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h4",{id:"new-features-2"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("h4",{id:"symfony"},"Symfony:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h4",{id:"laravel"},"Laravel:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h4",{id:"internals"},"Internals:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7110],{13401:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>d,contentTitle:()=>r,default:()=>u,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var t=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function u(e){let{components:a,...n}=e;return(0,i.yg)(g,(0,t.A)({},s,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"500"},"5.0.0"),(0,i.yg)("h4",{id:"dependencies"},"Dependencies:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.yg)("h2",{id:"430"},"4.3.0"),(0,i.yg)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The method ",(0,i.yg)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.yg)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.yg)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.yg)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h4",{id:"new-features"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/input-types#input-annotation"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h4",{id:"new-features-1"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h4",{id:"new-features-2"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("h4",{id:"symfony"},"Symfony:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h4",{id:"laravel"},"Laravel:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/5.0/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h4",{id:"internals"},"Internals:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/976f6afc.f299a405.js b/assets/js/976f6afc.88a5e9dd.js similarity index 99% rename from assets/js/976f6afc.f299a405.js rename to assets/js/976f6afc.88a5e9dd.js index 1b9173097..9cdbb57e0 100644 --- a/assets/js/976f6afc.f299a405.js +++ b/assets/js/976f6afc.88a5e9dd.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9717],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(o.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>A});var n=a(58168),r=a(96540),o=a(20053),u=a(23104),l=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(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 T(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},r.createElement(g,(0,n.A)({},e,t)),r.createElement(y,(0,n.A)({},e,t)))}function A(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},13769:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),o=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(m,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, mutations are created ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.1/queries"},"like queries"),"."),(0,r.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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([[9717],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(o.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>A});var n=a(58168),r=a(96540),o=a(20053),u=a(23104),l=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(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 T(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},r.createElement(g,(0,n.A)({},e,t)),r.createElement(y,(0,n.A)({},e,t)))}function A(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},13769:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),o=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(m,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, mutations are created ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.1/queries"},"like queries"),"."),(0,r.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.5b5ca3da.js b/assets/js/9953ecde.a070338d.js similarity index 98% rename from assets/js/9953ecde.5b5ca3da.js rename to assets/js/9953ecde.a070338d.js index 550843158..b738a3867 100644 --- a/assets/js/9953ecde.5b5ca3da.js +++ b/assets/js/9953ecde.a070338d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3308],{32608:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Attributes 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:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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([[3308],{32608:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Attributes 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:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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/999289d8.dac2cd6d.js b/assets/js/999289d8.73089ca7.js similarity index 99% rename from assets/js/999289d8.dac2cd6d.js rename to assets/js/999289d8.73089ca7.js index 017c1db43..64528454c 100644 --- a/assets/js/999289d8.dac2cd6d.js +++ b/assets/js/999289d8.73089ca7.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6253],{10138:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>d,toc:()=>s});var i=n(58168),a=(n(96540),n(15680));n(67443);const l={id:"field-middlewares",title:"Adding custom attributes with Field middlewares",sidebar_label:"Custom attributes"},r=void 0,d={unversionedId:"field-middlewares",id:"version-8.0.0/field-middlewares",title:"Adding custom attributes with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/field-middlewares.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom attributes with Field middlewares",sidebar_label:"Custom attributes"},sidebar:"docs",previous:{title:"Custom types",permalink:"/docs/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/argument-resolving"}},o={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Attributes parsing",id:"attributes-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:t,...l}=e;return(0,a.yg)(p,(0,i.A)({},u,l,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Logged]")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Right]")," attribute, you can develop your own attribute that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an attribute that targets a single argument (like ",(0,a.yg)("code",null,"#[AutoWire]"),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:n(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("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.yg)("h2",{id:"attributes-parsing"},"Attributes parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of attributes applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("inlineCode",{parentName:"p"},"#[OnlyDebug]")," attribute that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.yg)("p",null,"First, we have to define the attribute."),(0,a.yg)("pre",null,(0,a.yg)("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#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n")),(0,a.yg)("p",null,"Apart from being a classical attribute, this class implements the ",(0,a.yg)("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 attribute is to be used by middlewares.'),(0,a.yg)("p",null,"Now, we can write a middleware that will act upon this attribute."),(0,a.yg)("pre",null,(0,a.yg)("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 attribute 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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,t,n)=>{n.d(t,{A:()=>i});const i=n.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6253],{10138:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>o,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>d,toc:()=>s});var i=n(58168),a=(n(96540),n(15680));n(67443);const l={id:"field-middlewares",title:"Adding custom attributes with Field middlewares",sidebar_label:"Custom attributes"},r=void 0,d={unversionedId:"field-middlewares",id:"version-8.0.0/field-middlewares",title:"Adding custom attributes with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/field-middlewares.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom attributes with Field middlewares",sidebar_label:"Custom attributes"},sidebar:"docs",previous:{title:"Custom types",permalink:"/docs/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/argument-resolving"}},o={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Attributes parsing",id:"attributes-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:t,...l}=e;return(0,a.yg)(p,(0,i.A)({},u,l,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Logged]")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Right]")," attribute, you can develop your own attribute that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an attribute that targets a single argument (like ",(0,a.yg)("code",null,"#[AutoWire]"),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:n(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("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.yg)("h2",{id:"attributes-parsing"},"Attributes parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of attributes applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("inlineCode",{parentName:"p"},"#[OnlyDebug]")," attribute that displays a field/query/mutation only in debug mode (and\nhides the field in production). That could be useful, right?"),(0,a.yg)("p",null,"First, we have to define the attribute."),(0,a.yg)("pre",null,(0,a.yg)("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#[Attribute(Attribute::TARGET_METHOD)]\nclass OnlyDebug implements MiddlewareAnnotationInterface\n{\n}\n")),(0,a.yg)("p",null,"Apart from being a classical attribute, this class implements the ",(0,a.yg)("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 attribute is to be used by middlewares.'),(0,a.yg)("p",null,"Now, we can write a middleware that will act upon this attribute."),(0,a.yg)("pre",null,(0,a.yg)("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 attribute 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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,t,n)=>{n.d(t,{A:()=>i});const i=n.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/9bbf4a9a.abe2da8e.js b/assets/js/9bbf4a9a.f9d0f062.js similarity index 99% rename from assets/js/9bbf4a9a.abe2da8e.js rename to assets/js/9bbf4a9a.f9d0f062.js index f1618fec2..ba244a2dc 100644 --- a/assets/js/9bbf4a9a.abe2da8e.js +++ b/assets/js/9bbf4a9a.f9d0f062.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6681],{12736:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"version-8.0.0/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-8.0.0/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/migrating.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[SourceField]")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[SourceField]")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"#[MagicField]")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6681],{12736:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);const o={id:"migrating",title:"Migrating",sidebar_label:"Migrating"},r=void 0,l={unversionedId:"migrating",id:"version-8.0.0/migrating",title:"Migrating",description:"Migrating from v4.0 to v4.1",source:"@site/versioned_docs/version-8.0.0/migrating.md",sourceDirName:".",slug:"/migrating",permalink:"/docs/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/migrating.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[SourceField]")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[SourceField]")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"#[MagicField]")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9bd507da.8a54c024.js b/assets/js/9bd507da.346f47b6.js similarity index 98% rename from assets/js/9bd507da.8a54c024.js rename to assets/js/9bd507da.346f47b6.js index 9f6f0efac..12ba0c66f 100644 --- a/assets/js/9bd507da.8a54c024.js +++ b/assets/js/9bd507da.346f47b6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1565],{65890:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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([[1565],{65890:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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.a389bf5f.js b/assets/js/9d336ee4.5353010a.js similarity index 99% rename from assets/js/9d336ee4.a389bf5f.js rename to assets/js/9d336ee4.5353010a.js index 30f46dc62..42d693686 100644 --- a/assets/js/9d336ee4.a389bf5f.js +++ b/assets/js/9d336ee4.5353010a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9778],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),i=n(56347),s=n(57485),u=n(31682),p=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.W6)(),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.aZ)(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),[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]=y({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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),m=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);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 m=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":i===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 T(e){const t=g(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},50054:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 y(e){let{components:t,...i}=e;return(0,r.yg)(h,(0,a.A)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.yg)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.yg)("p",null,"Read the ",(0,r.yg)("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.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:n(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}y.isMDXComponent=!0},67258:(e,t,n)=>{n.d(t,{A:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9778],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),i=n(56347),s=n(57485),u=n(31682),p=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.W6)(),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.aZ)(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),[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]=y({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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),m=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);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 m=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":i===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 T(e){const t=g(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},50054:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 y(e){let{components:t,...i}=e;return(0,r.yg)(h,(0,a.A)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.yg)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.yg)("p",null,"Read the ",(0,r.yg)("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.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:n(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}y.isMDXComponent=!0},67258:(e,t,n)=>{n.d(t,{A:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/9d9f8394.3b18f36b.js b/assets/js/9d9f8394.722fb0cd.js similarity index 97% rename from assets/js/9d9f8394.3b18f36b.js rename to assets/js/9d9f8394.722fb0cd.js index af9d42b2e..82483b617 100644 --- a/assets/js/9d9f8394.3b18f36b.js +++ b/assets/js/9d9f8394.722fb0cd.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9013],{9036:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>a,default:()=>g,frontMatter:()=>i,metadata:()=>s,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9013],{9036:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>a,default:()=>g,frontMatter:()=>i,metadata:()=>s,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9f0ecd2e.5b766b08.js b/assets/js/9f0ecd2e.f474bd30.js similarity index 99% rename from assets/js/9f0ecd2e.5b766b08.js rename to assets/js/9f0ecd2e.f474bd30.js index b5230fae3..8a979b01e 100644 --- a/assets/js/9f0ecd2e.5b766b08.js +++ b/assets/js/9f0ecd2e.f474bd30.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4893],{70261:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(58168),a=(t(96540),t(15680));t(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.1/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/6.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.yg)(p,(0,i.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:t(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,n,t)=>{t.d(n,{A:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4893],{70261:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(58168),a=(t(96540),t(15680));t(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.1/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/6.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.yg)(p,(0,i.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:t(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,n,t)=>{t.d(n,{A:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/a0bf4a5f.acd35b74.js b/assets/js/a0bf4a5f.edd3ca79.js similarity index 99% rename from assets/js/a0bf4a5f.acd35b74.js rename to assets/js/a0bf4a5f.edd3ca79.js index b2583c887..e77a3a7ba 100644 --- a/assets/js/a0bf4a5f.acd35b74.js +++ b/assets/js/a0bf4a5f.edd3ca79.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4876],{49317:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(58168),a=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:t(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,n,t)=>{t.d(n,{A:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4876],{49317:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(58168),a=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:t(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,n,t)=>{t.d(n,{A:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/a13f3cdc.739720d4.js b/assets/js/a13f3cdc.bce6936a.js similarity index 99% rename from assets/js/a13f3cdc.739720d4.js rename to assets/js/a13f3cdc.bce6936a.js index f1047e291..e7487d022 100644 --- a/assets/js/a13f3cdc.739720d4.js +++ b/assets/js/a13f3cdc.bce6936a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[835],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(s.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),s=n(20053),o=n(23104),l=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("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 T(e){const t=f(e);return r.createElement("div",{className:(0,s.A)("tabs-container",y.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,b.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},34394:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),s=(n(67443),n(11470)),o=n(19365);const l={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.3/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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([[835],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(s.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),s=n(20053),o=n(23104),l=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("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 T(e){const t=f(e);return r.createElement("div",{className:(0,s.A)("tabs-container",y.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,b.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},34394:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),s=(n(67443),n(11470)),o=n(19365);const l={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.3/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.d02d6cc1.js b/assets/js/a16ee953.29db8d4b.js similarity index 99% rename from assets/js/a16ee953.d02d6cc1.js rename to assets/js/a16ee953.29db8d4b.js index 25b77e878..9d6cd3919 100644 --- a/assets/js/a16ee953.d02d6cc1.js +++ b/assets/js/a16ee953.29db8d4b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4224],{27244:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/6.0/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4224],{27244:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/6.0/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a1e3d512.6cf2b1e6.js b/assets/js/a1e3d512.8e8cc309.js similarity index 99% rename from assets/js/a1e3d512.6cf2b1e6.js rename to assets/js/a1e3d512.8e8cc309.js index b53149a7b..9f94d97d5 100644 --- a/assets/js/a1e3d512.6cf2b1e6.js +++ b/assets/js/a1e3d512.8e8cc309.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9949],{19365:(e,a,t)=>{t.d(a,{A:()=>o});var n=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:a,hidden:t,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function g(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function d(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,l.W6)(),i=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const a=new URLSearchParams(n.location.search);a.set(i,e),n.replace({...n.location,search:a.toString()})}),[i,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=g(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!d({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:i}))),[s,u]=y({queryString:t,groupId:n}),[c,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,i]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{m&&l(m)}),[m]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,i]),tabValues:i}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:a,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),g=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==l&&(c(a),s(n))},d=e=>{let a=null;switch(e.key){case"Enter":g(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:e=>p.push(e),onKeyDown:d,onClick:g},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===a})}),t??a)})))}function v(e){let{lazy:a,children:t,selectedValue:n}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function N(e){const a=h(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,a)),r.createElement(v,(0,n.A)({},e,a)))}function T(e){const a=(0,m.A)();return r.createElement(N,(0,n.A)({key:String(a)},e))}},26337:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>l,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);const l={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:c},d="wrapper";function y(e){let{components:a,...t}=e;return(0,r.yg)(d,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"If the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.1/authentication_authorization#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.yg)("li",{parentName:"ul"},"...")),(0,r.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.yg)("code",null,"@Security")," annotation and Symfony's ",(0,r.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.yg)("h2",{id:"the-is_granted-function"},"The ",(0,r.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.yg)("p",null,"is similar to"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.yg)("p",null,"In addition, the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"PHP 7")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.1/authentication_authorization#not-throwing-errors"},(0,r.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"You cannot use the ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.yg)("p",null,"If you are using Laravel, you will ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.yg)("p",null,"If you are using another framework, you need to know that the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.1/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9949],{19365:(e,a,t)=>{t.d(a,{A:()=>o});var n=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:a,hidden:t,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function g(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function d(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,l.W6)(),i=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const a=new URLSearchParams(n.location.search);a.set(i,e),n.replace({...n.location,search:a.toString()})}),[i,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=g(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!d({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:i}))),[s,u]=y({queryString:t,groupId:n}),[c,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,i]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{m&&l(m)}),[m]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,i]),tabValues:i}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:a,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),g=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==l&&(c(a),s(n))},d=e=>{let a=null;switch(e.key){case"Enter":g(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:e=>p.push(e),onKeyDown:d,onClick:g},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===a})}),t??a)})))}function v(e){let{lazy:a,children:t,selectedValue:n}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function N(e){const a=h(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,a)),r.createElement(v,(0,n.A)({},e,a)))}function T(e){const a=(0,m.A)();return r.createElement(N,(0,n.A)({key:String(a)},e))}},26337:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>l,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);const l={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:c},d="wrapper";function y(e){let{components:a,...t}=e;return(0,r.yg)(d,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"If the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.1/authentication_authorization#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.yg)("li",{parentName:"ul"},"...")),(0,r.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.yg)("code",null,"@Security")," annotation and Symfony's ",(0,r.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.yg)("h2",{id:"the-is_granted-function"},"The ",(0,r.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.yg)("p",null,"is similar to"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.yg)("p",null,"In addition, the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"PHP 7")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.1/authentication_authorization#not-throwing-errors"},(0,r.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"You cannot use the ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.yg)("p",null,"If you are using Laravel, you will ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.yg)("p",null,"If you are using another framework, you need to know that the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.1/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a228ae9b.49370dc4.js b/assets/js/a228ae9b.2a435235.js similarity index 99% rename from assets/js/a228ae9b.49370dc4.js rename to assets/js/a228ae9b.2a435235.js index d128f9c50..414349abd 100644 --- a/assets/js/a228ae9b.49370dc4.js +++ b/assets/js/a228ae9b.2a435235.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4619],{53556:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>l,default:()=>h,frontMatter:()=>o,metadata:()=>r,toc:()=>s});var a=n(58168),i=(n(96540),n(15680));n(67443);const o={id:"operation-complexity",title:"Operation complexity",sidebar_label:"Operation complexity"},l=void 0,r={unversionedId:"operation-complexity",id:"version-8.0.0/operation-complexity",title:"Operation complexity",description:"At some point you may find yourself receiving queries with an insane amount of requested",source:"@site/versioned_docs/version-8.0.0/operation-complexity.md",sourceDirName:".",slug:"/operation-complexity",permalink:"/docs/operation-complexity",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/operation-complexity.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"operation-complexity",title:"Operation complexity",sidebar_label:"Operation complexity"},sidebar:"docs",previous:{title:"Connecting security to your framework",permalink:"/docs/implementing-security"},next:{title:"Query plan",permalink:"/docs/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},y="wrapper";function h(e){let{components:t,...n}=e;return(0,i.yg)(y,(0,a.A)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("h2",{id:"query-depth"},"Query depth"),(0,i.yg)("p",null,"The simplest way to limit complexity is to limit the max query depth. ",(0,i.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php"),",\nwhich GraphQLite relies on, ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"addValidationRule")," when building your PSR15 middleware:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$builder->addValidationRule(new \\GraphQL\\Validator\\Rules\\QueryDepth(7));\n")),(0,i.yg)("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.yg)("h2",{id:"static-request-analysis"},"Static request analysis"),(0,i.yg)("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.yg)("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.yg)("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.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the above example executing the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field on the ",(0,i.yg)("inlineCode",{parentName:"p"},"Query")," type might go to the\ndatabase and fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"Book"),". This means that the cost of the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field is\nprobably higher than the cost of the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"title"),", the default\ncost of ",(0,i.yg)("inlineCode",{parentName:"p"},"1")," os OK. But for ",(0,i.yg)("inlineCode",{parentName:"p"},"books"),", we might want to go with a higher cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"10"),"\nsince we are getting a list of books from our database."),(0,i.yg)("p",null,"Moreover, we have the field ",(0,i.yg)("inlineCode",{parentName:"p"},"author")," on the book, which might go to the database\nas well to fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"Author")," object. Since we are only fetching a single item here,\nwe might want to apply a cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"5")," to this field."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"If we run the following query against our data graph, we will come up with the cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"11"),"."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.yg)("p",null,"When drilling in further, a cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"17")," occurs."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"10")," even though we might get one or one\nhundred books back?"),(0,i.yg)("h2",{id:"full-request-analysis"},"Full request analysis"),(0,i.yg)("p",null,"The operation complexity analyzer can also take arguments into account when analyzing operation complexity."),(0,i.yg)("p",null,"If we look at our data graph, we can see that the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field actually has an argument\nthat defines how many books are returned. The ",(0,i.yg)("inlineCode",{parentName:"p"},"take")," argument, in this case, specifies\nthe maximum books that the field will return."),(0,i.yg)("p",null,"When measuring the field","`","s impact, we can take the argument ",(0,i.yg)("inlineCode",{parentName:"p"},"take")," into account as a\nmultiplier of our cost. This means we might want to lower the cost to ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"take")," argument."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"With the multiplier in place, we now get a cost of ",(0,i.yg)("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.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"10 * (5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.yg)("p",null,"When drilling in further, the cost will go up to ",(0,i.yg)("inlineCode",{parentName:"p"},"240")," since we are now pulling twice as much books and also their authors."),(0,i.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"20 * (5 + 1 + 5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: 20) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("p",null,"Notice the nullable ",(0,i.yg)("inlineCode",{parentName:"p"},"$take")," parameter. This might come in handy if ",(0,i.yg)("inlineCode",{parentName:"p"},"take: null"),' means "get all items",\nbut that would also mean that the overall complexity would only be ',(0,i.yg)("inlineCode",{parentName:"p"},"1 + 5 + 1 + 5 + 1 = 11"),",\nwhen in fact that would be a very costly query to execute. "),(0,i.yg)("p",null,"If all of the multiplier fields are either ",(0,i.yg)("inlineCode",{parentName:"p"},"null")," or missing (and don't have default values),\n",(0,i.yg)("inlineCode",{parentName:"p"},"defaultMultiplier")," is used:"),(0,i.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"200 * (5 + 1 + 5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: null) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("h2",{id:"setup"},"Setup"),(0,i.yg)("p",null,"As with query depth, automatic query complexity is configured through PSR15 middleware:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Beware that introspection queries would also be limited in complexity. A full introspection\nquery sits at around ",(0,i.yg)("inlineCode",{parentName:"p"},"107")," points, so we recommend a minimum of ",(0,i.yg)("inlineCode",{parentName:"p"},"150")," for query complexity limit."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4619],{53556:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>l,default:()=>h,frontMatter:()=>o,metadata:()=>r,toc:()=>s});var a=n(58168),i=(n(96540),n(15680));n(67443);const o={id:"operation-complexity",title:"Operation complexity",sidebar_label:"Operation complexity"},l=void 0,r={unversionedId:"operation-complexity",id:"version-8.0.0/operation-complexity",title:"Operation complexity",description:"At some point you may find yourself receiving queries with an insane amount of requested",source:"@site/versioned_docs/version-8.0.0/operation-complexity.md",sourceDirName:".",slug:"/operation-complexity",permalink:"/docs/operation-complexity",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/operation-complexity.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"operation-complexity",title:"Operation complexity",sidebar_label:"Operation complexity"},sidebar:"docs",previous:{title:"Connecting security to your framework",permalink:"/docs/implementing-security"},next:{title:"Query plan",permalink:"/docs/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},y="wrapper";function h(e){let{components:t,...n}=e;return(0,i.yg)(y,(0,a.A)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("h2",{id:"query-depth"},"Query depth"),(0,i.yg)("p",null,"The simplest way to limit complexity is to limit the max query depth. ",(0,i.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php"),",\nwhich GraphQLite relies on, ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"addValidationRule")," when building your PSR15 middleware:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"$builder = new Psr15GraphQLMiddlewareBuilder($schema);\n\n$builder->addValidationRule(new \\GraphQL\\Validator\\Rules\\QueryDepth(7));\n")),(0,i.yg)("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.yg)("h2",{id:"static-request-analysis"},"Static request analysis"),(0,i.yg)("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.yg)("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.yg)("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.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the above example executing the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field on the ",(0,i.yg)("inlineCode",{parentName:"p"},"Query")," type might go to the\ndatabase and fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"Book"),". This means that the cost of the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field is\nprobably higher than the cost of the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"title"),", the default\ncost of ",(0,i.yg)("inlineCode",{parentName:"p"},"1")," os OK. But for ",(0,i.yg)("inlineCode",{parentName:"p"},"books"),", we might want to go with a higher cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"10"),"\nsince we are getting a list of books from our database."),(0,i.yg)("p",null,"Moreover, we have the field ",(0,i.yg)("inlineCode",{parentName:"p"},"author")," on the book, which might go to the database\nas well to fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"Author")," object. Since we are only fetching a single item here,\nwe might want to apply a cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"5")," to this field."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"If we run the following query against our data graph, we will come up with the cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"11"),"."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.yg)("p",null,"When drilling in further, a cost of ",(0,i.yg)("inlineCode",{parentName:"p"},"17")," occurs."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"10")," even though we might get one or one\nhundred books back?"),(0,i.yg)("h2",{id:"full-request-analysis"},"Full request analysis"),(0,i.yg)("p",null,"The operation complexity analyzer can also take arguments into account when analyzing operation complexity."),(0,i.yg)("p",null,"If we look at our data graph, we can see that the ",(0,i.yg)("inlineCode",{parentName:"p"},"books")," field actually has an argument\nthat defines how many books are returned. The ",(0,i.yg)("inlineCode",{parentName:"p"},"take")," argument, in this case, specifies\nthe maximum books that the field will return."),(0,i.yg)("p",null,"When measuring the field","`","s impact, we can take the argument ",(0,i.yg)("inlineCode",{parentName:"p"},"take")," into account as a\nmultiplier of our cost. This means we might want to lower the cost to ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"take")," argument."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"With the multiplier in place, we now get a cost of ",(0,i.yg)("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.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"10 * (5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books {\n title\n }\n}\n")),(0,i.yg)("p",null,"When drilling in further, the cost will go up to ",(0,i.yg)("inlineCode",{parentName:"p"},"240")," since we are now pulling twice as much books and also their authors."),(0,i.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"20 * (5 + 1 + 5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: 20) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("p",null,"Notice the nullable ",(0,i.yg)("inlineCode",{parentName:"p"},"$take")," parameter. This might come in handy if ",(0,i.yg)("inlineCode",{parentName:"p"},"take: null"),' means "get all items",\nbut that would also mean that the overall complexity would only be ',(0,i.yg)("inlineCode",{parentName:"p"},"1 + 5 + 1 + 5 + 1 = 11"),",\nwhen in fact that would be a very costly query to execute. "),(0,i.yg)("p",null,"If all of the multiplier fields are either ",(0,i.yg)("inlineCode",{parentName:"p"},"null")," or missing (and don't have default values),\n",(0,i.yg)("inlineCode",{parentName:"p"},"defaultMultiplier")," is used:"),(0,i.yg)("p",null,"Cost calculation: ",(0,i.yg)("inlineCode",{parentName:"p"},"200 * (5 + 1 + 5 + 1)")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"query {\n books(take: null) {\n title\n author {\n name\n }\n }\n}\n")),(0,i.yg)("h2",{id:"setup"},"Setup"),(0,i.yg)("p",null,"As with query depth, automatic query complexity is configured through PSR15 middleware:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Beware that introspection queries would also be limited in complexity. A full introspection\nquery sits at around ",(0,i.yg)("inlineCode",{parentName:"p"},"107")," points, so we recommend a minimum of ",(0,i.yg)("inlineCode",{parentName:"p"},"150")," for query complexity limit."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a23a5b68.67a39e10.js b/assets/js/a23a5b68.08f8a0a8.js similarity index 99% rename from assets/js/a23a5b68.67a39e10.js rename to assets/js/a23a5b68.08f8a0a8.js index 60b0b2511..8c559ae6f 100644 --- a/assets/js/a23a5b68.67a39e10.js +++ b/assets/js/a23a5b68.08f8a0a8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8093],{19365:(e,a,n)=>{n.d(a,{A:()=>i});var t=n(96540),r=n(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:a,hidden:n,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:n},a)}},11470:(e,a,n)=>{n.d(a,{A:()=>T});var t=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),p=n(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:n,attributes:t,default:r}}=e;return{value:a,label:n,attributes:t,default:r}}))}function d(e){const{values:a,children:n}=e;return(0,r.useMemo)((()=>{const e=a??c(n);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,n])}function g(e){let{value:a,tabValues:n}=e;return n.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:n}=e;const t=(0,o.W6)(),l=function(e){let{queryString:a=!1,groupId:n}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:n});return[(0,s.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(t.location.search);a.set(l,e),t.replace({...t.location,search:a.toString()})}),[l,t])]}function m(e){const{defaultValue:a,queryString:n=!1,groupId:t}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const t=n.find((e=>e.default))??n[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:a,tabValues:l}))),[s,u]=h({queryString:n,groupId:t}),[c,m]=function(e){let{groupId:a}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(a),[t,l]=(0,p.Dv)(n);return[t,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:t}),y=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,l]),tabValues:l}}var y=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const a=e.currentTarget,n=p.indexOf(a),t=u[n].value;t!==o&&(c(a),s(t))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;a=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;a=p[n]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":n},a)},u.map((e=>{let{value:a,label:n,attributes:i}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===a})}),n??a)})))}function b(e){let{lazy:a,children:n,selectedValue:t}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(a){const e=l.find((e=>e.props.value===t));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==t}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(v,(0,t.A)({},e,a)),r.createElement(b,(0,t.A)({},e,a)))}function T(e){const a=(0,y.A)();return r.createElement(w,(0,t.A)({key:String(a)},e))}},24483:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var t=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},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},g="wrapper";function h(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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'))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8093],{19365:(e,a,n)=>{n.d(a,{A:()=>i});var t=n(96540),r=n(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:a,hidden:n,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:n},a)}},11470:(e,a,n)=>{n.d(a,{A:()=>T});var t=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),p=n(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:n,attributes:t,default:r}}=e;return{value:a,label:n,attributes:t,default:r}}))}function d(e){const{values:a,children:n}=e;return(0,r.useMemo)((()=>{const e=a??c(n);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,n])}function g(e){let{value:a,tabValues:n}=e;return n.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:n}=e;const t=(0,o.W6)(),l=function(e){let{queryString:a=!1,groupId:n}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:n});return[(0,s.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(t.location.search);a.set(l,e),t.replace({...t.location,search:a.toString()})}),[l,t])]}function m(e){const{defaultValue:a,queryString:n=!1,groupId:t}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const t=n.find((e=>e.default))??n[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:a,tabValues:l}))),[s,u]=h({queryString:n,groupId:t}),[c,m]=function(e){let{groupId:a}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(a),[t,l]=(0,p.Dv)(n);return[t,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:t}),y=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,l]),tabValues:l}}var y=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const a=e.currentTarget,n=p.indexOf(a),t=u[n].value;t!==o&&(c(a),s(t))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;a=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;a=p[n]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":n},a)},u.map((e=>{let{value:a,label:n,attributes:i}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===a})}),n??a)})))}function b(e){let{lazy:a,children:n,selectedValue:t}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(a){const e=l.find((e=>e.props.value===t));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==t}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(v,(0,t.A)({},e,a)),r.createElement(b,(0,t.A)({},e,a)))}function T(e){const a=(0,y.A)();return r.createElement(w,(0,t.A)({key:String(a)},e))}},24483:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var t=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},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},g="wrapper";function h(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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'))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a264d631.df1707bf.js b/assets/js/a264d631.33587268.js similarity index 99% rename from assets/js/a264d631.df1707bf.js rename to assets/js/a264d631.33587268.js index e540250d3..de653bd5f 100644 --- a/assets/js/a264d631.df1707bf.js +++ b/assets/js/a264d631.33587268.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7542],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>w});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),c=t(31682),u=t(89466);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,c.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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,c]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,u.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),c(e),y(e)}),[c,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),h=e=>{const n=e.currentTarget,t=u.indexOf(n),r=c[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=u.indexOf(e.currentTarget)+1;n=u[t]??u[0];break}case"ArrowLeft":{const t=u.indexOf(e.currentTarget)-1;n=u[t]??u[u.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.A)("tabs__item",f.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 v(e){const n=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function w(e){const n=(0,m.A)();return a.createElement(v,(0,r.A)({key:String(n)},e))}},52541:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>c,toc:()=>p});var r=t(58168),a=(t(96540),t(15680)),o=(t(67443),t(11470)),i=t(19365);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,c={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},u={},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 g(e){let{components:n,...t}=e;return(0,a.yg)(d,(0,r.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/5.0/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/5.0/laravel-package"},"Laravel"),")."),(0,a.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7542],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>w});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),c=t(31682),u=t(89466);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,c.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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,c]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,u.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),c(e),y(e)}),[c,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),h=e=>{const n=e.currentTarget,t=u.indexOf(n),r=c[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=u.indexOf(e.currentTarget)+1;n=u[t]??u[0];break}case"ArrowLeft":{const t=u.indexOf(e.currentTarget)-1;n=u[t]??u[u.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.A)("tabs__item",f.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 v(e){const n=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function w(e){const n=(0,m.A)();return a.createElement(v,(0,r.A)({key:String(n)},e))}},52541:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>c,toc:()=>p});var r=t(58168),a=(t(96540),t(15680)),o=(t(67443),t(11470)),i=t(19365);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,c={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},u={},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 g(e){let{components:n,...t}=e;return(0,a.yg)(d,(0,r.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/5.0/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/5.0/laravel-package"},"Laravel"),")."),(0,a.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a27ea030.bb1f8d85.js b/assets/js/a27ea030.dc26afa1.js similarity index 98% rename from assets/js/a27ea030.bb1f8d85.js rename to assets/js/a27ea030.dc26afa1.js index 848bbe47b..dcf2ca7fa 100644 --- a/assets/js/a27ea030.bb1f8d85.js +++ b/assets/js/a27ea030.dc26afa1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[68],{95007:(e,t,r)=>{r.r(t),r.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>h,frontMatter:()=>n,metadata:()=>u,toc:()=>d});var i=r(58168),s=(r(96540),r(15680)),a=r(67443);const n={id:"automatic-persisted-queries",title:"Automatic persisted queries",sidebar_label:"Automatic persisted queries"},o=void 0,u={unversionedId:"automatic-persisted-queries",id:"version-7.0.0/automatic-persisted-queries",title:"Automatic persisted queries",description:"The problem",source:"@site/versioned_docs/version-7.0.0/automatic-persisted-queries.mdx",sourceDirName:".",slug:"/automatic-persisted-queries",permalink:"/docs/7.0.0/automatic-persisted-queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/automatic-persisted-queries.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"automatic-persisted-queries",title:"Automatic persisted queries",sidebar_label:"Automatic persisted queries"},sidebar:"docs",previous:{title:"Prefetching records",permalink:"/docs/7.0.0/prefetch-method"},next:{title:"File uploads",permalink:"/docs/7.0.0/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.yg)(c,(0,i.A)({},p,r,{components:t,mdxType:"MDXLayout"}),(0,s.yg)("h2",{id:"the-problem"},"The problem"),(0,s.yg)("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.yg)("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.yg)("h2",{id:"apollo-apq"},"Apollo APQ"),(0,s.yg)("p",null,(0,s.yg)("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.yg)("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.yg)(a.K,{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.yg)("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.yg)("p",null,"Because query identifiers are deterministic hashes, clients can generate them at runtime. No additional build steps are required."),(0,s.yg)("h2",{id:"setup"},"Setup"),(0,s.yg)("p",null,"To use Automatic persisted queries with GraphQLite, you may use\n",(0,s.yg)("inlineCode",{parentName:"p"},"useAutomaticPersistedQueries")," method when building your PSR-15 middleware:"),(0,s.yg)("pre",null,(0,s.yg)("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([[68],{95007:(e,t,r)=>{r.r(t),r.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>h,frontMatter:()=>n,metadata:()=>u,toc:()=>d});var i=r(58168),s=(r(96540),r(15680)),a=r(67443);const n={id:"automatic-persisted-queries",title:"Automatic persisted queries",sidebar_label:"Automatic persisted queries"},o=void 0,u={unversionedId:"automatic-persisted-queries",id:"version-7.0.0/automatic-persisted-queries",title:"Automatic persisted queries",description:"The problem",source:"@site/versioned_docs/version-7.0.0/automatic-persisted-queries.mdx",sourceDirName:".",slug:"/automatic-persisted-queries",permalink:"/docs/7.0.0/automatic-persisted-queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/automatic-persisted-queries.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"automatic-persisted-queries",title:"Automatic persisted queries",sidebar_label:"Automatic persisted queries"},sidebar:"docs",previous:{title:"Prefetching records",permalink:"/docs/7.0.0/prefetch-method"},next:{title:"File uploads",permalink:"/docs/7.0.0/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.yg)(c,(0,i.A)({},p,r,{components:t,mdxType:"MDXLayout"}),(0,s.yg)("h2",{id:"the-problem"},"The problem"),(0,s.yg)("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.yg)("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.yg)("h2",{id:"apollo-apq"},"Apollo APQ"),(0,s.yg)("p",null,(0,s.yg)("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.yg)("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.yg)(a.K,{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.yg)("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.yg)("p",null,"Because query identifiers are deterministic hashes, clients can generate them at runtime. No additional build steps are required."),(0,s.yg)("h2",{id:"setup"},"Setup"),(0,s.yg)("p",null,"To use Automatic persisted queries with GraphQLite, you may use\n",(0,s.yg)("inlineCode",{parentName:"p"},"useAutomaticPersistedQueries")," method when building your PSR-15 middleware:"),(0,s.yg)("pre",null,(0,s.yg)("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/a27f6be0.c080cf87.js b/assets/js/a27f6be0.d4e018f5.js similarity index 98% rename from assets/js/a27f6be0.c080cf87.js rename to assets/js/a27f6be0.d4e018f5.js index 74d655189..d636b7026 100644 --- a/assets/js/a27f6be0.c080cf87.js +++ b/assets/js/a27f6be0.d4e018f5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1062],{78291:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>p,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},c={},u=[],l={toc:u},g="wrapper";function p(e){let{components:t,...n}=e;return(0,r.yg)(g,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--info"},"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package"),(0,r.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.1/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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([[1062],{78291:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>p,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},c={},u=[],l={toc:u},g="wrapper";function p(e){let{components:t,...n}=e;return(0,r.yg)(g,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--info"},"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package"),(0,r.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.1/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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/a28aff23.142ca450.js b/assets/js/a28aff23.a3f13e2b.js similarity index 99% rename from assets/js/a28aff23.142ca450.js rename to assets/js/a28aff23.a3f13e2b.js index b7a61325d..4c22a86e4 100644 --- a/assets/js/a28aff23.142ca450.js +++ b/assets/js/a28aff23.a3f13e2b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6337],{19365:(e,n,t)=>{t.d(n,{A:()=>o});var a=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:n,hidden:t,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>I});var a=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function d(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 h(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??d(t);return function(e){const n=(0,s.X)(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 p(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,l.W6)(),i=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.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function m(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=h(e),[o,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(!p({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:i}))),[u,s]=g({queryString:t,groupId:a}),[d,m]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),y=(()=>{const e=u??d;return p({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),m(e)}),[s,m,i]),tabValues:i}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},p=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 r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function N(e){const n=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function I(e){const n=(0,y.A)();return r.createElement(N,(0,a.A)({key:String(n)},e))}},32488:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>g,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],h={toc:d},p="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(p,(0,a.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.yg)("a",{parentName:"li",href:"/docs/6.0/fine-grained-security"},(0,r.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.yg)("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.yg)("br",null),"See ",(0,r.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.yg)("h2",{id:"logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.yg)("p",null,"GraphQLite exposes two annotations (",(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the query ",(0,r.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/6.0/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.yg)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6337],{19365:(e,n,t)=>{t.d(n,{A:()=>o});var a=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:n,hidden:t,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>I});var a=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function d(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 h(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??d(t);return function(e){const n=(0,s.X)(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 p(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,l.W6)(),i=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.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function m(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=h(e),[o,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(!p({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:i}))),[u,s]=g({queryString:t,groupId:a}),[d,m]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),y=(()=>{const e=u??d;return p({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),m(e)}),[s,m,i]),tabValues:i}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},p=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 r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function N(e){const n=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function I(e){const n=(0,y.A)();return r.createElement(N,(0,a.A)({key:String(n)},e))}},32488:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>g,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],h={toc:d},p="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(p,(0,a.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.yg)("a",{parentName:"li",href:"/docs/6.0/fine-grained-security"},(0,r.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.yg)("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.yg)("br",null),"See ",(0,r.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.yg)("h2",{id:"logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.yg)("p",null,"GraphQLite exposes two annotations (",(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the query ",(0,r.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/6.0/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.yg)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a2d3d8d2.827b3b19.js b/assets/js/a2d3d8d2.de206452.js similarity index 99% rename from assets/js/a2d3d8d2.827b3b19.js rename to assets/js/a2d3d8d2.de206452.js index 4374f6ff9..e486a7602 100644 --- a/assets/js/a2d3d8d2.827b3b19.js +++ b/assets/js/a2d3d8d2.de206452.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6123],{19365:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(96540),r=a(20053);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.A)(l.tabItem,i),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>x});var n=a(58168),r=a(96540),l=a(20053),i=a(23104),o=a(56347),u=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(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(!y({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,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return y({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),h(e)}),[s,h,l]),tabValues:l}}var f=a(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},y=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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:y,onClick:d},i,{className:(0,l.A)("tabs__item",g.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 T(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",g.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function x(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},59490:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/extend-type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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([[6123],{19365:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(96540),r=a(20053);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.A)(l.tabItem,i),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>x});var n=a(58168),r=a(96540),l=a(20053),i=a(23104),o=a(56347),u=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(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(!y({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,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return y({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),h(e)}),[s,h,l]),tabValues:l}}var f=a(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},y=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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:y,onClick:d},i,{className:(0,l.A)("tabs__item",g.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 T(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",g.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function x(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},59490:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/extend-type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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/a30fd8ca.6e705d12.js b/assets/js/a30fd8ca.1c3c185f.js similarity index 99% rename from assets/js/a30fd8ca.6e705d12.js rename to assets/js/a30fd8ca.1c3c185f.js index 9fd1cd057..d80ec3727 100644 --- a/assets/js/a30fd8ca.6e705d12.js +++ b/assets/js/a30fd8ca.1c3c185f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[501],{19365:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(96540),r=a(20053);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.A)(l.tabItem,i),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>x});var n=a(58168),r=a(96540),l=a(20053),i=a(23104),o=a(56347),u=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(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(!y({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,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return y({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),h(e)}),[s,h,l]),tabValues:l}}var f=a(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},y=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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:y,onClick:d},i,{className:(0,l.A)("tabs__item",g.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 T(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",g.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function x(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},22061:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.1/extend_type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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([[501],{19365:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(96540),r=a(20053);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.A)(l.tabItem,i),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>x});var n=a(58168),r=a(96540),l=a(20053),i=a(23104),o=a(56347),u=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(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(!y({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,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,p.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??c;return y({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),h(e)}),[s,h,l]),tabValues:l}}var f=a(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,a=p.indexOf(t),n=s[a].value;n!==o&&(c(t),u(n))},y=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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>p.push(e),onKeyDown:y,onClick:d},i,{className:(0,l.A)("tabs__item",g.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 T(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",g.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function x(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},22061:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>u,default:()=>m,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.1/extend_type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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/a320b509.dcda4ae0.js b/assets/js/a320b509.567f3680.js similarity index 99% rename from assets/js/a320b509.dcda4ae0.js rename to assets/js/a320b509.567f3680.js index 1347020c7..2a02ab93f 100644 --- a/assets/js/a320b509.dcda4ae0.js +++ b/assets/js/a320b509.567f3680.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4779],{87719:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(58168),a=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour\nof a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:t(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"OnlyDebug.php")),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:",(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"li"},"graphql.field_middleware")," tag.")))}c.isMDXComponent=!0},8643:(e,n,t)=>{t.d(n,{A:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4779],{87719:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(58168),a=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour\nof a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:t(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"OnlyDebug.php")),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:",(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"li"},"graphql.field_middleware")," tag.")))}c.isMDXComponent=!0},8643:(e,n,t)=>{t.d(n,{A:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/a3a193a6.9cd17649.js b/assets/js/a3a193a6.b4dee0e0.js similarity index 98% rename from assets/js/a3a193a6.9cd17649.js rename to assets/js/a3a193a6.b4dee0e0.js index 65b888ad9..c47057956 100644 --- a/assets/js/a3a193a6.9cd17649.js +++ b/assets/js/a3a193a6.b4dee0e0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[464],{7254:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},u="wrapper";function d(e){let{components:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental"),"\nand their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"li"},"composer.json"),", target a major version:",(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"li"},"composer.json"),", target a minor version:",(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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([[464],{7254:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},u="wrapper";function d(e){let{components:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental"),"\nand their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"li"},"composer.json"),", target a major version:",(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"li"},"composer.json"),", target a minor version:",(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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/a3c6f073.978dd91e.js b/assets/js/a3c6f073.0ee436f4.js similarity index 98% rename from assets/js/a3c6f073.978dd91e.js rename to assets/js/a3c6f073.0ee436f4.js index a2363b9f7..46bb3e4bc 100644 --- a/assets/js/a3c6f073.978dd91e.js +++ b/assets/js/a3c6f073.0ee436f4.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8588],{12775:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>i,default:()=>d,frontMatter:()=>s,metadata:()=>o,toc:()=>h});var a=n(58168),r=(n(96540),n(15680));n(67443);const s={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,o={unversionedId:"prefetch-method",id:"version-8.0.0/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/prefetch-method.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"docs",previous:{title:"Query plan",permalink:"/docs/query-plan"},next:{title:"Automatic persisted queries",permalink:"/docs/automatic-persisted-queries"}},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},c="wrapper";function d(e){let{components:t,...n}=e;return(0,r.yg)(c,(0,a.A)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When a ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Prefetch]")," attribute is detected on a parameter of ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute, the method is called automatically.\nThe prefetch callable must be one of the following:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a static method in the same class: ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Prefetch('prefetchMethod')]")),(0,r.yg)("li",{parentName:"ul"},"a static method in a different class: ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Prefetch([OtherClass::class, 'prefetchMethod')]")),(0,r.yg)("li",{parentName:"ul"},"a non-static method in a different class, resolvable through the container: ",(0,r.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," annotated method OR/AND on the prefetch methods."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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')))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8588],{12775:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>i,default:()=>d,frontMatter:()=>s,metadata:()=>o,toc:()=>h});var a=n(58168),r=(n(96540),n(15680));n(67443);const s={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,o={unversionedId:"prefetch-method",id:"version-8.0.0/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/prefetch-method.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},sidebar:"docs",previous:{title:"Query plan",permalink:"/docs/query-plan"},next:{title:"Automatic persisted queries",permalink:"/docs/automatic-persisted-queries"}},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},c="wrapper";function d(e){let{components:t,...n}=e;return(0,r.yg)(c,(0,a.A)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When a ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Prefetch]")," attribute is detected on a parameter of ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute, the method is called automatically.\nThe prefetch callable must be one of the following:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a static method in the same class: ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Prefetch('prefetchMethod')]")),(0,r.yg)("li",{parentName:"ul"},"a static method in a different class: ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Prefetch([OtherClass::class, 'prefetchMethod')]")),(0,r.yg)("li",{parentName:"ul"},"a non-static method in a different class, resolvable through the container: ",(0,r.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," annotated method OR/AND on the prefetch methods."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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')))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a55b0daf.785d30b6.js b/assets/js/a55b0daf.6caf9e22.js similarity index 99% rename from assets/js/a55b0daf.785d30b6.js rename to assets/js/a55b0daf.6caf9e22.js index cadb74dd8..fbb597171 100644 --- a/assets/js/a55b0daf.785d30b6.js +++ b/assets/js/a55b0daf.6caf9e22.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9441],{26884:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>l,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(58168),t=(a(96540),a(15680));a(67443);const i={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},o=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},l={},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:"Disabling autoloading",id:"disabling-autoloading",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,...a}=e;return(0,t.yg)(d,(0,r.A)({},c,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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->addNamespace('App');\n\n$schema = $factory->createSchema();\n")),(0,t.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the #[Logged] attributes).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the #[Right] attributes).\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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h3",{id:"disabling-autoloading"},"Disabling autoloading"),(0,t.yg)("p",null,"GraphQLite uses ",(0,t.yg)("inlineCode",{parentName:"p"},"kcs/class-finder")," to find all classes that have GraphQLite attributes. By default, it uses\nautoloading under the hood. But if you have an older codebase that contains classes with incorrect or missing\nnamespaces, you may need to use ",(0,t.yg)("inlineCode",{parentName:"p"},"include_once")," instead. To do so, you can overwrite the finder using ",(0,t.yg)("inlineCode",{parentName:"p"},"setFinder()"),":"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use Kcs\\ClassFinder\\Finder\\ComposerFinder;\nuse TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n$factory = new SchemaFactory($cache, $container);\n$factory->addNamespace('App')\n ->setFinder(\n (new ComposerFinder())->useAutoloading(false)\n );\n\n$schema = $factory->createSchema();\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"addNamespace('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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.laminas.dev/laminas-stratigility/"},"Laminas Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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 "laminas/laminas-diactoros": "^2",\n "laminas/laminas-stratigility": "^3",\n "laminas/laminas-httphandlerrunner": "^2",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Laminas ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Laminas Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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 // Any PSR-16 cache should work - APCu is recommended for good\n // performance, but it requires that module to be enabled. For\n // small scale testing with zero dependencies, FilesystemCache\n // can be used instead.\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->addNamespace('App');\n return $factory->createSchema();\n }\n]);\n")),(0,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9441],{26884:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>l,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(58168),t=(a(96540),a(15680));a(67443);const i={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},o=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},l={},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:"Disabling autoloading",id:"disabling-autoloading",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,...a}=e;return(0,t.yg)(d,(0,r.A)({},c,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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->addNamespace('App');\n\n$schema = $factory->createSchema();\n")),(0,t.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the #[Logged] attributes).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the #[Right] attributes).\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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h3",{id:"disabling-autoloading"},"Disabling autoloading"),(0,t.yg)("p",null,"GraphQLite uses ",(0,t.yg)("inlineCode",{parentName:"p"},"kcs/class-finder")," to find all classes that have GraphQLite attributes. By default, it uses\nautoloading under the hood. But if you have an older codebase that contains classes with incorrect or missing\nnamespaces, you may need to use ",(0,t.yg)("inlineCode",{parentName:"p"},"include_once")," instead. To do so, you can overwrite the finder using ",(0,t.yg)("inlineCode",{parentName:"p"},"setFinder()"),":"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use Kcs\\ClassFinder\\Finder\\ComposerFinder;\nuse TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n$factory = new SchemaFactory($cache, $container);\n$factory->addNamespace('App')\n ->setFinder(\n (new ComposerFinder())->useAutoloading(false)\n );\n\n$schema = $factory->createSchema();\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"addNamespace('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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.laminas.dev/laminas-stratigility/"},"Laminas Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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 "laminas/laminas-diactoros": "^2",\n "laminas/laminas-stratigility": "^3",\n "laminas/laminas-httphandlerrunner": "^2",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Laminas ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Laminas Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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 // Any PSR-16 cache should work - APCu is recommended for good\n // performance, but it requires that module to be enabled. For\n // small scale testing with zero dependencies, FilesystemCache\n // can be used instead.\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->addNamespace('App');\n return $factory->createSchema();\n }\n]);\n")),(0,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a9125b44.2b3ca9e8.js b/assets/js/a9125b44.76fd5a69.js similarity index 99% rename from assets/js/a9125b44.2b3ca9e8.js rename to assets/js/a9125b44.76fd5a69.js index aa1622dd7..8efedae3e 100644 --- a/assets/js/a9125b44.2b3ca9e8.js +++ b/assets/js/a9125b44.76fd5a69.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2301],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),i=n(56347),s=n(57485),u=n(31682),p=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.W6)(),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.aZ)(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),[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]=y({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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),m=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);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 m=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":i===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 T(e){const t=g(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},50257:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},s=void 0,u={unversionedId:"queries",id:"version-7.0.0/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-7.0.0/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/7.0.0/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/queries.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/7.0.0/other-frameworks"},next:{title:"Mutations",permalink:"/docs/7.0.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 y(e){let{components:t,...i}=e;return(0,r.yg)(h,(0,a.A)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.yg)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.yg)("p",null,"Read the ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:n(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}y.isMDXComponent=!0},67258:(e,t,n)=>{n.d(t,{A:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2301],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),i=n(56347),s=n(57485),u=n(31682),p=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{queryString:t=!1,groupId:n}=e;const a=(0,i.W6)(),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.aZ)(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),[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]=y({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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),m=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);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 m=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":i===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 T(e){const t=g(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},50257:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},s=void 0,u={unversionedId:"queries",id:"version-7.0.0/queries",title:"Queries",description:"In GraphQLite, GraphQL queries are created by writing methods in controller classes.",source:"@site/versioned_docs/version-7.0.0/queries.mdx",sourceDirName:".",slug:"/queries",permalink:"/docs/7.0.0/queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/queries.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"queries",title:"Queries",sidebar_label:"Queries"},sidebar:"docs",previous:{title:"Other frameworks / No framework",permalink:"/docs/7.0.0/other-frameworks"},next:{title:"Mutations",permalink:"/docs/7.0.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 y(e){let{components:t,...i}=e;return(0,r.yg)(h,(0,a.A)({},d,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.yg)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.yg)("p",null,"Read the ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/doctrine-annotations-attributes"},"Doctrine annotations VS attributes")," documentation if you are not familiar with this concept."),(0,r.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:n(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}y.isMDXComponent=!0},67258:(e,t,n)=>{n.d(t,{A:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/a91c1a62.0e26beae.js b/assets/js/a91c1a62.7c3e335b.js similarity index 97% rename from assets/js/a91c1a62.0e26beae.js rename to assets/js/a91c1a62.7c3e335b.js index 8fb6011df..3eb76f89a 100644 --- a/assets/js/a91c1a62.0e26beae.js +++ b/assets/js/a91c1a62.7c3e335b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6219],{89813:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-7.0.0/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-7.0.0/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/7.0.0/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/troubleshooting.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/7.0.0/internals"},next:{title:"Migrating",permalink:"/docs/7.0.0/migrating"}},l={},u=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6219],{89813:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-7.0.0/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-7.0.0/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/7.0.0/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/troubleshooting.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/7.0.0/internals"},next:{title:"Migrating",permalink:"/docs/7.0.0/migrating"}},l={},u=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a95c9e82.c54a1418.js b/assets/js/a95c9e82.cf629d6f.js similarity index 99% rename from assets/js/a95c9e82.c54a1418.js rename to assets/js/a95c9e82.cf629d6f.js index 41659efc1..c574cf5f7 100644 --- a/assets/js/a95c9e82.c54a1418.js +++ b/assets/js/a95c9e82.cf629d6f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8309],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(o.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>A});var n=a(58168),r=a(96540),o=a(20053),u=a(23104),l=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(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 T(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},r.createElement(g,(0,n.A)({},e,t)),r.createElement(y,(0,n.A)({},e,t)))}function A(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},40963:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),o=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(m,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, mutations are created ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/queries"},"like queries"),"."),(0,r.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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([[8309],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(o.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>A});var n=a(58168),r=a(96540),o=a(20053),u=a(23104),l=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(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 T(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},r.createElement(g,(0,n.A)({},e,t)),r.createElement(y,(0,n.A)({},e,t)))}function A(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},40963:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),o=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(m,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, mutations are created ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/queries"},"like queries"),"."),(0,r.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.6c07b693.js b/assets/js/a99e9943.c61535a0.js similarity index 98% rename from assets/js/a99e9943.6c07b693.js rename to assets/js/a99e9943.c61535a0.js index 5b04ee5cb..a4b25a203 100644 --- a/assets/js/a99e9943.6c07b693.js +++ b/assets/js/a99e9943.c61535a0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9866],{91357:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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([[9866],{91357:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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.08cf572d.js b/assets/js/a9bc4f03.79e0d8ad.js similarity index 99% rename from assets/js/a9bc4f03.08cf572d.js rename to assets/js/a9bc4f03.79e0d8ad.js index d9f6241ff..a59fcd549 100644 --- a/assets/js/a9bc4f03.08cf572d.js +++ b/assets/js/a9bc4f03.79e0d8ad.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[629],{14711:(a,e,t)=>{t.r(e),t.d(e,{assets:()=>s,contentTitle:()=>r,default:()=>y,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 y(a){let{components:e,...t}=a;return(0,i.yg)(p,(0,n.A)({},u,t,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box"),(0,i.yg)("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.yg)("em",{parentName:"li"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:",(0,i.yg)("pre",{parentName:"li"},(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"UserController.php")),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"User.php")),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,i.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,i.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.yg)("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.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.yg)("p",null,"You can also pass an array to the ",(0,i.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[629],{14711:(a,e,t)=>{t.r(e),t.d(e,{assets:()=>s,contentTitle:()=>r,default:()=>y,frontMatter:()=>o,metadata:()=>l,toc:()=>d});var n=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 y(a){let{components:e,...t}=a;return(0,i.yg)(p,(0,n.A)({},u,t,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box"),(0,i.yg)("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.yg)("em",{parentName:"li"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:",(0,i.yg)("pre",{parentName:"li"},(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"UserController.php")),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"User.php")),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,i.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,i.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.yg)("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.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.yg)("p",null,"You can also pass an array to the ",(0,i.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/aa52484c.81674c15.js b/assets/js/aa52484c.1be28e63.js similarity index 98% rename from assets/js/aa52484c.81674c15.js rename to assets/js/aa52484c.1be28e63.js index af2f39a70..baa2787da 100644 --- a/assets/js/aa52484c.81674c15.js +++ b/assets/js/aa52484c.1be28e63.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4919],{18328:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>t,metadata:()=>s,toc:()=>l});var n=i(58168),a=(i(96540),i(15680));i(67443);const t={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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,a.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,a.yg)("p",null,(0,a.yg)("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,a.yg)("p",null,"If your framework is compatible with ",(0,a.yg)("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,a.yg)("h2",{id:"installation"},"Installation"),(0,a.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,a.yg)("h2",{id:"requirements"},"Requirements"),(0,a.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,a.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,a.yg)("p",null,"GraphQLite relies on the ",(0,a.yg)("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,a.yg)("a",{parentName:"p",href:"/docs/4.0/other-frameworks"},"PSR-15 middleware"),"."),(0,a.yg)("h2",{id:"integration"},"Integration"),(0,a.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,a.yg)("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,a.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,a.yg)("p",null,(0,a.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,a.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,a.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"composer.json")),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"index.php")),(0,a.yg)("pre",null,(0,a.yg)("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([[4919],{18328:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>t,metadata:()=>s,toc:()=>l});var n=i(58168),a=(i(96540),i(15680));i(67443);const t={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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,a.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,a.yg)("p",null,(0,a.yg)("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,a.yg)("p",null,"If your framework is compatible with ",(0,a.yg)("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,a.yg)("h2",{id:"installation"},"Installation"),(0,a.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,a.yg)("h2",{id:"requirements"},"Requirements"),(0,a.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,a.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,a.yg)("p",null,"GraphQLite relies on the ",(0,a.yg)("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,a.yg)("a",{parentName:"p",href:"/docs/4.0/other-frameworks"},"PSR-15 middleware"),"."),(0,a.yg)("h2",{id:"integration"},"Integration"),(0,a.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,a.yg)("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,a.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,a.yg)("p",null,(0,a.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,a.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,a.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"composer.json")),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"index.php")),(0,a.yg)("pre",null,(0,a.yg)("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.41588e8b.js b/assets/js/aa5b6080.202b05d1.js similarity index 99% rename from assets/js/aa5b6080.41588e8b.js rename to assets/js/aa5b6080.202b05d1.js index 5c1c39934..5f42d3f1e 100644 --- a/assets/js/aa5b6080.41588e8b.js +++ b/assets/js/aa5b6080.202b05d1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1894],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),r=n(20053);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.A)(l.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),p=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.W6)(),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.aZ)(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]=y({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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),m=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);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 m=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",f.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 T(e){const t=g(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},35913:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 y(e){let{components:t,...o}=e;return(0,r.yg)(h,(0,a.A)({},d,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.yg)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.yg)("p",null,"Read the ",(0,r.yg)("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.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:n(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}y.isMDXComponent=!0},67258:(e,t,n)=>{n.d(t,{A:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1894],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),r=n(20053);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.A)(l.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),p=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.W6)(),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.aZ)(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]=y({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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),m=(()=>{const e=s??c;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);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 m=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",f.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 T(e){const t=g(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},35913:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 y(e){let{components:t,...o}=e;return(0,r.yg)(h,(0,a.A)({},d,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-annotations--attributes"},"About annotations / attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on annotations (we call them attributes since PHP 8)."),(0,r.yg)("p",null,'It supports both the old "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),") and the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),")."),(0,r.yg)("p",null,"Read the ",(0,r.yg)("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.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:n(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}y.isMDXComponent=!0},67258:(e,t,n)=>{n.d(t,{A:()=>a});const a=n.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/aa675676.70580274.js b/assets/js/aa675676.65e35c40.js similarity index 99% rename from assets/js/aa675676.70580274.js rename to assets/js/aa675676.65e35c40.js index 687b29dd8..61c94d745 100644 --- a/assets/js/aa675676.70580274.js +++ b/assets/js/aa675676.65e35c40.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2358],{19365:(e,a,t)=>{t.d(a,{A:()=>o});var n=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:a,hidden:t,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>N});var n=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),s=t(57485),u=t(31682),d=t(89466);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function c(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??p(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function m(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:t}=e;const n=(0,l.W6)(),i=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const a=new URLSearchParams(n.location.search);a.set(i,e),n.replace({...n.location,search:a.toString()})}),[i,n])]}function y(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!m({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:i}))),[s,u]=h({queryString:t,groupId:n}),[p,y]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,i]=(0,d.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:n}),g=(()=>{const e=s??p;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),y(e)}),[u,y,i]),tabValues:i}}var g=t(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:a,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),c=e=>{const a=e.currentTarget,t=d.indexOf(a),n=u[t].value;n!==l&&(p(a),s(n))},m=e=>{let a=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const t=d.indexOf(e.currentTarget)+1;a=d[t]??d[0];break}case"ArrowLeft":{const t=d.indexOf(e.currentTarget)-1;a=d[t]??d[d.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.A)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=y(e);return r.createElement("div",{className:(0,i.A)("tabs-container",v.tabList)},r.createElement(f,(0,n.A)({},e,a)),r.createElement(b,(0,n.A)({},e,a)))}function N(e){const a=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},52268:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,r.yg)(m,(0,n.A)({},c,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box"),(0,r.yg)("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.yg)("em",{parentName:"li"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:",(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"UserController.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"UserController.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"User.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"User.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,r.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.yg)("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.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.yg)("p",null,"You can also pass an array to the ",(0,r.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.yg)("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([[2358],{19365:(e,a,t)=>{t.d(a,{A:()=>o});var n=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:a,hidden:t,className:o}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>N});var n=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),s=t(57485),u=t(31682),d=t(89466);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function c(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??p(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function m(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:t}=e;const n=(0,l.W6)(),i=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const a=new URLSearchParams(n.location.search);a.set(i,e),n.replace({...n.location,search:a.toString()})}),[i,n])]}function y(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=c(e),[o,l]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!m({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:i}))),[s,u]=h({queryString:t,groupId:n}),[p,y]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,i]=(0,d.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:n}),g=(()=>{const e=s??p;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),y(e)}),[u,y,i]),tabValues:i}}var g=t(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:a,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),c=e=>{const a=e.currentTarget,t=d.indexOf(a),n=u[t].value;n!==l&&(p(a),s(n))},m=e=>{let a=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const t=d.indexOf(e.currentTarget)+1;a=d[t]??d[0];break}case"ArrowLeft":{const t=d.indexOf(e.currentTarget)-1;a=d[t]??d[d.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:e=>d.push(e),onKeyDown:m,onClick:c},o,{className:(0,i.A)("tabs__item",v.tabItem,o?.className,{"tabs__item--active":l===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=y(e);return r.createElement("div",{className:(0,i.A)("tabs-container",v.tabList)},r.createElement(f,(0,n.A)({},e,a)),r.createElement(b,(0,n.A)({},e,a)))}function N(e){const a=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},52268:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,r.yg)(m,(0,n.A)({},c,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,r.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,r.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,r.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box"),(0,r.yg)("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.yg)("em",{parentName:"li"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:",(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,r.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"UserController.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"UserController.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"User.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"User.php")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,r.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,r.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,r.yg)("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.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,r.yg)("p",null,"You can also pass an array to the ",(0,r.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,r.yg)("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/aba5bf07.ba5e1374.js b/assets/js/aba5bf07.0d27af80.js similarity index 99% rename from assets/js/aba5bf07.ba5e1374.js rename to assets/js/aba5bf07.0d27af80.js index d98529c0f..bbd069508 100644 --- a/assets/js/aba5bf07.ba5e1374.js +++ b/assets/js/aba5bf07.0d27af80.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3955],{19365:(e,n,t)=>{t.d(n,{A:()=>r});var a=t(96540),o=t(20053);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.A)(i.tabItem,r),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>A});var a=t(58168),o=t(96540),i=t(20053),r=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.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:o}}=e;return{value:n,label:t,attributes:a,default:o}}))}function d(e){const{values:n,children:t}=e;return(0,o.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 y(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,l.W6)(),i=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.aZ)(i),(0,o.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.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(!y({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:i}))),[u,s]=h({queryString:t,groupId:a}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,o.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),m=(()=>{const e=u??p;return y({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{m&&l(m)}),[m]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!y({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(p(n),u(a))},y=e=>{let n=null;switch(e.key){case"Enter":d(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 o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:r}=e;return o.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:y,onClick:d},r,{className:(0,i.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===n})}),t??n)})))}function T(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,o.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=g(e);return o.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},o.createElement(b,(0,a.A)({},e,n)),o.createElement(T,(0,a.A)({},e,n)))}function A(e){const n=(0,m.A)();return o.createElement(v,(0,a.A)({key:String(n)},e))}},7168:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>h,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=t(58168),o=(t(96540),t(15680)),i=(t(67443),t(11470)),r=t(19365);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-7.0.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-7.0.0/external-type-declaration.mdx",sourceDirName:".",slug:"/external-type-declaration",permalink:"/docs/7.0.0/external-type-declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/external-type-declaration.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},sidebar:"docs",previous:{title:"Extending a type",permalink:"/docs/7.0.0/extend-type"},next:{title:"Input types",permalink:"/docs/7.0.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},y="wrapper";function h(e){let{components:n,...t}=e;return(0,o.yg)(y,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.yg)("p",null,"For instance:"),(0,o.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,o.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.yg)("p",null,"GraphQLite allows you to use a ",(0,o.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!")," The ",(0,o.yg)("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.yg)("br",null),(0,o.yg)("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.yg)("p",null,"In methods with a ",(0,o.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.yg)("h2",{id:"sourcefield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.yg)("p",null,"If you don't want to rewrite all ",(0,o.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("h2",{id:"magicfield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"Any annotations described in the ",(0,o.yg)("a",{parentName:"p",href:"/docs/7.0.0/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/7.0.0/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.yg)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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")))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3955],{19365:(e,n,t)=>{t.d(n,{A:()=>r});var a=t(96540),o=t(20053);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.A)(i.tabItem,r),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>A});var a=t(58168),o=t(96540),i=t(20053),r=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.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:o}}=e;return{value:n,label:t,attributes:a,default:o}}))}function d(e){const{values:n,children:t}=e;return(0,o.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 y(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,l.W6)(),i=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.aZ)(i),(0,o.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.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(!y({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:i}))),[u,s]=h({queryString:t,groupId:a}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,o.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),m=(()=>{const e=u??p;return y({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{m&&l(m)}),[m]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!y({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(p(n),u(a))},y=e=>{let n=null;switch(e.key){case"Enter":d(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 o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:r}=e;return o.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:y,onClick:d},r,{className:(0,i.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===n})}),t??n)})))}function T(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,o.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=g(e);return o.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},o.createElement(b,(0,a.A)({},e,n)),o.createElement(T,(0,a.A)({},e,n)))}function A(e){const n=(0,m.A)();return o.createElement(v,(0,a.A)({key:String(n)},e))}},7168:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>h,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=t(58168),o=(t(96540),t(15680)),i=(t(67443),t(11470)),r=t(19365);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-7.0.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-7.0.0/external-type-declaration.mdx",sourceDirName:".",slug:"/external-type-declaration",permalink:"/docs/7.0.0/external-type-declaration",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/external-type-declaration.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},sidebar:"docs",previous:{title:"Extending a type",permalink:"/docs/7.0.0/extend-type"},next:{title:"Input types",permalink:"/docs/7.0.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},y="wrapper";function h(e){let{components:n,...t}=e;return(0,o.yg)(y,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.yg)("p",null,"For instance:"),(0,o.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,o.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.yg)("p",null,"GraphQLite allows you to use a ",(0,o.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!")," The ",(0,o.yg)("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.yg)("br",null),(0,o.yg)("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.yg)("p",null,"In methods with a ",(0,o.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.yg)("h2",{id:"sourcefield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.yg)("p",null,"If you don't want to rewrite all ",(0,o.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("h2",{id:"magicfield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"Any annotations described in the ",(0,o.yg)("a",{parentName:"p",href:"/docs/7.0.0/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/7.0.0/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.yg)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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")))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/ac8293fa.486d62f6.js b/assets/js/ac8293fa.0add98f9.js similarity index 99% rename from assets/js/ac8293fa.486d62f6.js rename to assets/js/ac8293fa.0add98f9.js index 8b4c54dfe..7e5f5d7c8 100644 --- a/assets/js/ac8293fa.486d62f6.js +++ b/assets/js/ac8293fa.0add98f9.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[630],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(l.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),l=a(20053),u=a(23104),o=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.W6)(),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.aZ)(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 h(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]=g({queryString:a,groupId:n}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);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),h(e)}),[i,h,l]),tabValues:l}}var b=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.tabItem,u?.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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(f,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function T(e){const t=(0,b.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},89018:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/6.0/getting-started"}},c={},p=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[630],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(l.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),l=a(20053),u=a(23104),o=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.W6)(),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.aZ)(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 h(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]=g({queryString:a,groupId:n}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);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),h(e)}),[i,h,l]),tabValues:l}}var b=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.tabItem,u?.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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(f,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function T(e){const t=(0,b.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},89018:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/6.0/getting-started"}},c={},p=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/acbaac14.ade72d33.js b/assets/js/acbaac14.459d0ef1.js similarity index 99% rename from assets/js/acbaac14.ade72d33.js rename to assets/js/acbaac14.459d0ef1.js index adb539521..2dde5cf03 100644 --- a/assets/js/acbaac14.ade72d33.js +++ b/assets/js/acbaac14.459d0ef1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8483],{19365:(e,a,t)=>{t.d(a,{A:()=>l});var n=t(96540),r=t(20053);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:a,hidden:t,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(o.tabItem,l),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),o=t(20053),l=t(23104),i=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function g(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function d(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,i.W6)(),o=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(o),(0,r.useCallback)((e=>{if(!o)return;const a=new URLSearchParams(n.location.search);a.set(o,e),n.replace({...n.location,search:a.toString()})}),[o,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,o=g(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!d({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:o}))),[s,u]=y({queryString:t,groupId:n}),[c,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,o]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:a,block:t,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.a_)(),g=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==i&&(c(a),s(n))},d=e=>{let a=null;switch(e.key){case"Enter":g(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:l}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:i===a?0:-1,"aria-selected":i===a,key:a,ref:e=>p.push(e),onKeyDown:d,onClick:g},l,{className:(0,o.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":i===a})}),t??a)})))}function v(e){let{lazy:a,children:t,selectedValue:n}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function N(e){const a=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,a)),r.createElement(v,(0,n.A)({},e,a)))}function T(e){const a=(0,m.A)();return r.createElement(N,(0,n.A)({key:String(a)},e))}},66503:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),o=(t(67443),t(11470)),l=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:c},d="wrapper";function y(e){let{components:a,...t}=e;return(0,r.yg)(d,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"If the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/authentication-authorization#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.yg)("li",{parentName:"ul"},"...")),(0,r.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.yg)("code",null,"@Security")," annotation and Symfony's ",(0,r.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.yg)("h2",{id:"the-is_granted-function"},"The ",(0,r.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.yg)("p",null,"is similar to"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.yg)("p",null,"In addition, the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/authentication-authorization#not-throwing-errors"},(0,r.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"You cannot use the ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.yg)("p",null,"If you are using Laravel, you will ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.yg)("p",null,"If you are using another framework, you need to know that the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8483],{19365:(e,a,t)=>{t.d(a,{A:()=>l});var n=t(96540),r=t(20053);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:a,hidden:t,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(o.tabItem,l),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),o=t(20053),l=t(23104),i=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function g(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function d(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,i.W6)(),o=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(o),(0,r.useCallback)((e=>{if(!o)return;const a=new URLSearchParams(n.location.search);a.set(o,e),n.replace({...n.location,search:a.toString()})}),[o,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,o=g(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!d({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:o}))),[s,u]=y({queryString:t,groupId:n}),[c,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,o]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:a,block:t,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.a_)(),g=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==i&&(c(a),s(n))},d=e=>{let a=null;switch(e.key){case"Enter":g(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:l}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:i===a?0:-1,"aria-selected":i===a,key:a,ref:e=>p.push(e),onKeyDown:d,onClick:g},l,{className:(0,o.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":i===a})}),t??a)})))}function v(e){let{lazy:a,children:t,selectedValue:n}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function N(e){const a=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,a)),r.createElement(v,(0,n.A)({},e,a)))}function T(e){const a=(0,m.A)();return r.createElement(N,(0,n.A)({key:String(a)},e))}},66503:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),o=(t(67443),t(11470)),l=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:c},d="wrapper";function y(e){let{components:a,...t}=e;return(0,r.yg)(d,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"If the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/authentication-authorization#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.yg)("li",{parentName:"ul"},"...")),(0,r.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.yg)("code",null,"@Security")," annotation and Symfony's ",(0,r.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.yg)("h2",{id:"the-is_granted-function"},"The ",(0,r.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.yg)("p",null,"is similar to"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.yg)("p",null,"In addition, the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/authentication-authorization#not-throwing-errors"},(0,r.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"You cannot use the ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.yg)("p",null,"If you are using Laravel, you will ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.yg)("p",null,"If you are using another framework, you need to know that the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/ae0a12ed.4d52e402.js b/assets/js/ae0a12ed.dd201707.js similarity index 99% rename from assets/js/ae0a12ed.4d52e402.js rename to assets/js/ae0a12ed.dd201707.js index eb9cf1d53..8159566aa 100644 --- a/assets/js/ae0a12ed.4d52e402.js +++ b/assets/js/ae0a12ed.dd201707.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2998],{19365:(e,a,t)=>{t.d(a,{A:()=>l});var n=t(96540),r=t(20053);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:a,hidden:t,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(o.tabItem,l),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),o=t(20053),l=t(23104),i=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function g(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function d(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,i.W6)(),o=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(o),(0,r.useCallback)((e=>{if(!o)return;const a=new URLSearchParams(n.location.search);a.set(o,e),n.replace({...n.location,search:a.toString()})}),[o,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,o=g(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!d({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:o}))),[s,u]=y({queryString:t,groupId:n}),[c,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,o]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:a,block:t,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.a_)(),g=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==i&&(c(a),s(n))},d=e=>{let a=null;switch(e.key){case"Enter":g(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:l}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:i===a?0:-1,"aria-selected":i===a,key:a,ref:e=>p.push(e),onKeyDown:d,onClick:g},l,{className:(0,o.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":i===a})}),t??a)})))}function v(e){let{lazy:a,children:t,selectedValue:n}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function N(e){const a=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,a)),r.createElement(v,(0,n.A)({},e,a)))}function T(e){const a=(0,m.A)();return r.createElement(N,(0,n.A)({key:String(a)},e))}},91830:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),o=(t(67443),t(11470)),l=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:c},d="wrapper";function y(e){let{components:a,...t}=e;return(0,r.yg)(d,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"If the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/authentication-authorization#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.yg)("li",{parentName:"ul"},"...")),(0,r.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.yg)("code",null,"@Security")," annotation and Symfony's ",(0,r.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.yg)("h2",{id:"the-is_granted-function"},"The ",(0,r.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.yg)("p",null,"is similar to"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.yg)("p",null,"In addition, the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/authentication-authorization#not-throwing-errors"},(0,r.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"You cannot use the ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.yg)("p",null,"If you are using Laravel, you will ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.yg)("p",null,"If you are using another framework, you need to know that the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2998],{19365:(e,a,t)=>{t.d(a,{A:()=>l});var n=t(96540),r=t(20053);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:a,hidden:t,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(o.tabItem,l),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),o=t(20053),l=t(23104),i=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function g(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function d(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,i.W6)(),o=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(o),(0,r.useCallback)((e=>{if(!o)return;const a=new URLSearchParams(n.location.search);a.set(o,e),n.replace({...n.location,search:a.toString()})}),[o,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,o=g(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!d({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:o}))),[s,u]=y({queryString:t,groupId:n}),[c,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,o]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:a,block:t,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.a_)(),g=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==i&&(c(a),s(n))},d=e=>{let a=null;switch(e.key){case"Enter":g(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:l}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:i===a?0:-1,"aria-selected":i===a,key:a,ref:e=>p.push(e),onKeyDown:d,onClick:g},l,{className:(0,o.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":i===a})}),t??a)})))}function v(e){let{lazy:a,children:t,selectedValue:n}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function N(e){const a=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,a)),r.createElement(v,(0,n.A)({},e,a)))}function T(e){const a=(0,m.A)();return r.createElement(N,(0,n.A)({key:String(a)},e))}},91830:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),o=(t(67443),t(11470)),l=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:c},d="wrapper";function y(e){let{components:a,...t}=e;return(0,r.yg)(d,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"If the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/authentication-authorization#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.yg)("li",{parentName:"ul"},"...")),(0,r.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.yg)("code",null,"@Security")," annotation and Symfony's ",(0,r.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.yg)("h2",{id:"the-is_granted-function"},"The ",(0,r.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.yg)("p",null,"is similar to"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.yg)("p",null,"In addition, the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/authentication-authorization#not-throwing-errors"},(0,r.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"You cannot use the ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.yg)("p",null,"If you are using Laravel, you will ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.yg)("p",null,"If you are using another framework, you need to know that the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/aebf35b6.36a1f25d.js b/assets/js/aebf35b6.76f4300b.js similarity index 99% rename from assets/js/aebf35b6.36a1f25d.js rename to assets/js/aebf35b6.76f4300b.js index 0e22a876d..87afccaec 100644 --- a/assets/js/aebf35b6.36a1f25d.js +++ b/assets/js/aebf35b6.76f4300b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8357],{53682:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>p,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(r,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.yg)("h2",{id:"example"},"Example"),(0,i.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares a ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/external_type_declaration"},'"external" type')," mapping the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.yg)("p",null,"First of all, we specify ",(0,i.yg)("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.yg)("p",null,"Then, we specify ",(0,i.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,i.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,i.yg)("p",null,"Finally, we can write our requests:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,i.yg)("p",null,"Is a result, when the end user calls the ",(0,i.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,i.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,i.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,i.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,i.yg)("p",null,"If you want to extend a type using the ",(0,i.yg)("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.yg)("p",null,"So instead of writing:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")),(0,i.yg)("p",null,"you will write:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')),(0,i.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8357],{53682:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>p,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(r,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.yg)("h2",{id:"example"},"Example"),(0,i.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares a ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/external_type_declaration"},'"external" type')," mapping the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,i.yg)("p",null,"First of all, we specify ",(0,i.yg)("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.yg)("p",null,"Then, we specify ",(0,i.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,i.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,i.yg)("p",null,"Finally, we can write our requests:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,i.yg)("p",null,"Is a result, when the end user calls the ",(0,i.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,i.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,i.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,i.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,i.yg)("p",null,"If you want to extend a type using the ",(0,i.yg)("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.yg)("p",null,"So instead of writing:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")),(0,i.yg)("p",null,"you will write:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')),(0,i.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b06c439f.00df55b4.js b/assets/js/b06c439f.8519d884.js similarity index 99% rename from assets/js/b06c439f.00df55b4.js rename to assets/js/b06c439f.8519d884.js index 77549bf3c..431fd4408 100644 --- a/assets/js/b06c439f.00df55b4.js +++ b/assets/js/b06c439f.8519d884.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7906],{99687:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/4.3/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7906],{99687:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/4.3/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b0ed7ea5.d01ca2bb.js b/assets/js/b0ed7ea5.2f596615.js similarity index 99% rename from assets/js/b0ed7ea5.d01ca2bb.js rename to assets/js/b0ed7ea5.2f596615.js index 99196f31d..ed2cb85fe 100644 --- a/assets/js/b0ed7ea5.d01ca2bb.js +++ b/assets/js/b0ed7ea5.2f596615.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7940],{19365:(e,n,t)=>{t.d(n,{A:()=>r});var a=t(96540),o=t(20053);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.A)(i.tabItem,r),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>A});var a=t(58168),o=t(96540),i=t(20053),r=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.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:o}}=e;return{value:n,label:t,attributes:a,default:o}}))}function d(e){const{values:n,children:t}=e;return(0,o.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 y(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,l.W6)(),i=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.aZ)(i),(0,o.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.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(!y({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:i}))),[u,s]=h({queryString:t,groupId:a}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,o.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),m=(()=>{const e=u??p;return y({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{m&&l(m)}),[m]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!y({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(p(n),u(a))},y=e=>{let n=null;switch(e.key){case"Enter":d(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 o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:r}=e;return o.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:y,onClick:d},r,{className:(0,i.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===n})}),t??n)})))}function T(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,o.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=g(e);return o.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},o.createElement(b,(0,a.A)({},e,n)),o.createElement(T,(0,a.A)({},e,n)))}function A(e){const n=(0,m.A)();return o.createElement(v,(0,a.A)({key:String(n)},e))}},12940:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>h,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=t(58168),o=(t(96540),t(15680)),i=(t(67443),t(11470)),r=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:n,...t}=e;return(0,o.yg)(y,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.yg)("p",null,"For instance:"),(0,o.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,o.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.yg)("p",null,"GraphQLite allows you to use a ",(0,o.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!")," The ",(0,o.yg)("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.yg)("br",null),(0,o.yg)("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.yg)("p",null,"In methods with a ",(0,o.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.yg)("h2",{id:"sourcefield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.yg)("p",null,"If you don't want to rewrite all ",(0,o.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.yg)("h2",{id:"magicfield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"Any annotations described in the ",(0,o.yg)("a",{parentName:"p",href:"/docs/4.1/authentication_authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/4.1/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.yg)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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")))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7940],{19365:(e,n,t)=>{t.d(n,{A:()=>r});var a=t(96540),o=t(20053);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.A)(i.tabItem,r),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>A});var a=t(58168),o=t(96540),i=t(20053),r=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.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:o}}=e;return{value:n,label:t,attributes:a,default:o}}))}function d(e){const{values:n,children:t}=e;return(0,o.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 y(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,l.W6)(),i=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.aZ)(i),(0,o.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.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(!y({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:i}))),[u,s]=h({queryString:t,groupId:a}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,o.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),m=(()=>{const e=u??p;return y({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{m&&l(m)}),[m]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!y({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(p(n),u(a))},y=e=>{let n=null;switch(e.key){case"Enter":d(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 o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:r}=e;return o.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:y,onClick:d},r,{className:(0,i.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===n})}),t??n)})))}function T(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,o.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=g(e);return o.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},o.createElement(b,(0,a.A)({},e,n)),o.createElement(T,(0,a.A)({},e,n)))}function A(e){const n=(0,m.A)();return o.createElement(v,(0,a.A)({key:String(n)},e))}},12940:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>h,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=t(58168),o=(t(96540),t(15680)),i=(t(67443),t(11470)),r=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:n,...t}=e;return(0,o.yg)(y,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.yg)("p",null,"For instance:"),(0,o.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,o.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.yg)("p",null,"GraphQLite allows you to use a ",(0,o.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!")," The ",(0,o.yg)("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.yg)("br",null),(0,o.yg)("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.yg)("p",null,"In methods with a ",(0,o.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.yg)("h2",{id:"sourcefield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.yg)("p",null,"If you don't want to rewrite all ",(0,o.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.yg)("h2",{id:"magicfield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"Any annotations described in the ",(0,o.yg)("a",{parentName:"p",href:"/docs/4.1/authentication_authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/4.1/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.yg)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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")))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b103c05a.5b731e8a.js b/assets/js/b103c05a.7389b7f1.js similarity index 99% rename from assets/js/b103c05a.5b731e8a.js rename to assets/js/b103c05a.7389b7f1.js index c0df85ad4..d65a066e0 100644 --- a/assets/js/b103c05a.5b731e8a.js +++ b/assets/js/b103c05a.7389b7f1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3672],{10724:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>p,toc:()=>y});var n=a(58168),r=(a(96540),a(15680));a(67443);const l={id:"annotations-reference",title:"Attributes reference",sidebar_label:"Attributes reference"},i=void 0,p={unversionedId:"annotations-reference",id:"annotations-reference",title:"Attributes reference",description:"Note: all annotations are available in PHP 8 attribute format (#[Query]), support of Doctrine annotation format was dropped.",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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"annotations-reference",title:"Attributes reference",sidebar_label:"Attributes reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/next/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/next/semver"}},g={},y=[{value:"#Query",id:"query",level:2},{value:"#Mutation",id:"mutation",level:2},{value:"#Subscription",id:"subscription",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}],o={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},o,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Note: all annotations are available in PHP 8 attribute format (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),"), support of Doctrine annotation format was dropped.\nSee ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,r.yg)("h2",{id:"query"},"#","[Query]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]")," attribute is used to declare a GraphQL query."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,r.yg)("h2",{id:"mutation"},"#","[Mutation]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," attribute is used to declare a GraphQL mutation."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,r.yg)("h2",{id:"subscription"},"#","[Subscription]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute is used to declare a GraphQL subscription."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the subscription. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Defines the GraphQL output type that will be sent for the subscription.")))),(0,r.yg)("h2",{id:"type"},"#","[Type]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute 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,r.yg)("a",{parentName:"p",href:"#input-annotation"},"#[Input] attribute")," directly on the input type or a ",(0,r.yg)("a",{parentName:"p",href:"#factory-annotation"},"#[Factory] attribute")," to make/return an input type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"class"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("em",{parentName:"td"},"is passed"),", ",(0,r.yg)("a",{parentName:"td",href:"/docs/next/external-type-declaration"},"the class/enum annotated with ",(0,r.yg)("inlineCode",{parentName:"a"},"#[Type]")," becomes a service"),".")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"default"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,r.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"external"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,r.yg)("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,r.yg)("h2",{id:"extendtype"},"#","[ExtendType]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute is used to add fields to an existing GraphQL object type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"class"),(0,r.yg)("td",{parentName:"tr",align:null},"see below"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,r.yg)("a",{parentName:"td",href:"/docs/next/extend-type"},"The class annotated with ",(0,r.yg)("inlineCode",{parentName:"a"},"#[ExtendType]")," is a service"),".")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},"see below"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,r.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,r.yg)("h2",{id:"input"},"#","[Input]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute is used to declare a GraphQL input type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"default"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,r.yg)("inlineCode",{parentName:"td"},"true")," ",(0,r.yg)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,r.yg)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,r.yg)("inlineCode",{parentName:"td"},"true")," when ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," is used.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"update"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,r.yg)("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/subscription. This primarily applies to nullable fields.")))),(0,r.yg)("h2",{id:"field"},"#","[Field]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute is used to declare a GraphQL field."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," or ",(0,r.yg)("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,r.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,r.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,r.yg)("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,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"for"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string, array"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/next/input-types"},"inputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,r.yg)("h2",{id:"sourcefield"},"#","[SourceField]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," attribute is used to declare a GraphQL field."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"phpType"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"annotations"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"array\\"),(0,r.yg)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "#',"[Logged]",'" or "#',"[Right]",'" attribute as class here.')))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Note"),": ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,r.yg)("h2",{id:"magicfield"},"#","[MagicField]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[MagicField]")," attribute is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,r.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no"),"(*)"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"phpType"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no"),"(*)"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"annotations"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"array\\"),(0,r.yg)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "#',"[Logged]",'" or "#',"[Right]",'" attribute as class here.')))),(0,r.yg)("p",null,"(*) ",(0,r.yg)("strong",{parentName:"p"},"Note"),": ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,r.yg)("h2",{id:"prefetch"},"#","[Prefetch]"),(0,r.yg)("p",null,"Marks field parameter to be used for ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/prefetch-method"},"prefetching"),"."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": parameters of methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"callable"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"callable"),(0,r.yg)("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,r.yg)("h2",{id:"logged"},"#","[Logged]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," attribute is used to declare a Query/Mutation/Field is only visible to logged users."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("p",null,"This attribute allows no arguments."),(0,r.yg)("h2",{id:"right"},"#","[Right]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attribute is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,r.yg)("h2",{id:"failwith"},"#","[FailWith]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," attribute is used to declare a default value to return in the user is not authorized to see a specific\nquery/mutation/subscription/field (according to the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes)."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," and one of ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"value"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"mixed"),(0,r.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,r.yg)("h2",{id:"hideifunauthorized"},"#","[HideIfUnauthorized]"),(0,r.yg)("div",{class:"alert alert--warning"},"This attribute 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,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[HideIfUnauthorized]")," attribute is used to completely hide the query/mutation/subscription/field if the user is not authorized\nto access it (according to the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes)."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," and one of ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"#[HideIfUnauthorized]")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," are mutually exclusive."),(0,r.yg)("h2",{id:"injectuser"},"#","[InjectUser]"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[InjectUser]")," attribute to inject an instance of the current user logged in into a parameter of your\nquery/mutation/subscription/field."),(0,r.yg)("p",null,"See ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/authentication-authorization"},"the authentication and authorization page")," for more details."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,r.yg)("h2",{id:"security"},"#","[Security]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute 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,r.yg)("p",null,"See ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/fine-grained-security"},"the fine grained security page")," for more details."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"default")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,r.yg)("h2",{id:"factory"},"#","[Factory]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Factory]")," attribute is used to declare a factory that turns GraphQL input types into objects."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"default"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"If ",(0,r.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,r.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,r.yg)("a",{parentName:"td",href:"/docs/next/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,r.yg)("inlineCode",{parentName:"a"},"#[Parameter]")," attribute"),".")))),(0,r.yg)("h2",{id:"useinputtype"},"#","[UseInputType]"),(0,r.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"inputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,r.yg)("h2",{id:"decorate"},"#","[Decorate]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Decorate]")," attribute is used ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,r.yg)("inlineCode",{parentName:"a"},"#[Factory]")," attribute"),"."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,r.yg)("h2",{id:"autowire"},"#","[Autowire]"),(0,r.yg)("p",null,(0,r.yg)("a",{parentName:"p",href:"/docs/next/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,r.yg)("p",null,"Useful to inject services directly into ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," method arguments."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"identifier")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("h2",{id:"hideparameter"},"#","[HideParameter]"),(0,r.yg)("p",null,"Removes ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,r.yg)("h2",{id:"cost"},"#","[Cost]"),(0,r.yg)("p",null,"Sets complexity and multipliers on fields for ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/operation-complexity#static-request-analysis"},"automatic query complexity"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"complexity")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"int"),(0,r.yg)("td",{parentName:"tr",align:null},"Complexity for that field")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"multipliers")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"array\\"),(0,r.yg)("td",{parentName:"tr",align:null},"Names of fields by value of which complexity will be multiplied")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"defaultMultiplier")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"int"),(0,r.yg)("td",{parentName:"tr",align:null},"Default multiplier value if all multipliers are missing/null")))),(0,r.yg)("h2",{id:"validate"},"#","[Validate]"),(0,r.yg)("div",{class:"alert alert--info"},"This attribute is only available in the GraphQLite Laravel package"),(0,r.yg)("p",null,(0,r.yg)("a",{parentName:"p",href:"/docs/next/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Factory]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Decorator]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"rule")),(0,r.yg)("td",{parentName:"tr",align:null},"*yes"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,r.yg)("p",null,"Sample:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Validate(for: "$email", rule: "email|unique:users")]\n')),(0,r.yg)("h2",{id:"assertion"},"#","[Assertion]"),(0,r.yg)("p",null,(0,r.yg)("a",{parentName:"p",href:"/docs/next/validation"},"Validates a user input"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Assertion]")," attribute is available in the ",(0,r.yg)("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,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Factory]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Decorator]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"constraint")),(0,r.yg)("td",{parentName:"tr",align:null},"*yes"),(0,r.yg)("td",{parentName:"tr",align:null},"annotation"),(0,r.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation attributes.")))),(0,r.yg)("h2",{id:"enumtype"},(0,r.yg)("del",{parentName:"h2"},"@EnumType")),(0,r.yg)("p",null,(0,r.yg)("em",{parentName:"p"},"Deprecated: Use ",(0,r.yg)("a",{parentName:"em",href:"https://www.php.net/manual/en/language.types.enumerations.php"},"PHP 8.1's native Enums")," instead with a ",(0,r.yg)("a",{parentName:"em",href:"#type-annotation"},"#[Type]"),".")),(0,r.yg)("p",null,"The ",(0,r.yg)("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,r.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,r.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3672],{10724:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>l,metadata:()=>p,toc:()=>y});var n=a(58168),r=(a(96540),a(15680));a(67443);const l={id:"annotations-reference",title:"Attributes reference",sidebar_label:"Attributes reference"},i=void 0,p={unversionedId:"annotations-reference",id:"annotations-reference",title:"Attributes reference",description:"Note: all annotations are available in PHP 8 attribute format (#[Query]), support of Doctrine annotation format was dropped.",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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"annotations-reference",title:"Attributes reference",sidebar_label:"Attributes reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/next/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/next/semver"}},g={},y=[{value:"#Query",id:"query",level:2},{value:"#Mutation",id:"mutation",level:2},{value:"#Subscription",id:"subscription",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}],o={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},o,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Note: all annotations are available in PHP 8 attribute format (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),"), support of Doctrine annotation format was dropped.\nSee ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,r.yg)("h2",{id:"query"},"#","[Query]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]")," attribute is used to declare a GraphQL query."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,r.yg)("h2",{id:"mutation"},"#","[Mutation]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," attribute is used to declare a GraphQL mutation."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,r.yg)("h2",{id:"subscription"},"#","[Subscription]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Subscription]")," attribute is used to declare a GraphQL subscription."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the subscription. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Defines the GraphQL output type that will be sent for the subscription.")))),(0,r.yg)("h2",{id:"type"},"#","[Type]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute 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,r.yg)("a",{parentName:"p",href:"#input-annotation"},"#[Input] attribute")," directly on the input type or a ",(0,r.yg)("a",{parentName:"p",href:"#factory-annotation"},"#[Factory] attribute")," to make/return an input type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"class"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("em",{parentName:"td"},"is passed"),", ",(0,r.yg)("a",{parentName:"td",href:"/docs/next/external-type-declaration"},"the class/enum annotated with ",(0,r.yg)("inlineCode",{parentName:"a"},"#[Type]")," becomes a service"),".")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"default"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,r.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"external"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,r.yg)("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,r.yg)("h2",{id:"extendtype"},"#","[ExtendType]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," attribute is used to add fields to an existing GraphQL object type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"class"),(0,r.yg)("td",{parentName:"tr",align:null},"see below"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,r.yg)("a",{parentName:"td",href:"/docs/next/extend-type"},"The class annotated with ",(0,r.yg)("inlineCode",{parentName:"a"},"#[ExtendType]")," is a service"),".")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},"see below"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,r.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,r.yg)("h2",{id:"input"},"#","[Input]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute is used to declare a GraphQL input type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Description of the input type in the documentation. If not passed, PHP doc comment is used.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"default"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Name of the input type represented in your GraphQL schema. Defaults to ",(0,r.yg)("inlineCode",{parentName:"td"},"true")," ",(0,r.yg)("em",{parentName:"td"},"only if")," the name is not specified. If ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," is specified, this will default to ",(0,r.yg)("inlineCode",{parentName:"td"},"false"),", so must also be included for ",(0,r.yg)("inlineCode",{parentName:"td"},"true")," when ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," is used.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"update"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"Determines if the the input represents a partial update. When set to ",(0,r.yg)("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/subscription. This primarily applies to nullable fields.")))),(0,r.yg)("h2",{id:"field"},"#","[Field]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute is used to declare a GraphQL field."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties of classes annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]")," or ",(0,r.yg)("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,r.yg)("inlineCode",{parentName:"p"},"foo")," then getter should be ",(0,r.yg)("inlineCode",{parentName:"p"},"getFoo()")," or setter should be ",(0,r.yg)("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,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"for"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string, array"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If it's empty PHP doc comment is used instead.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/next/input-types"},"inputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL input type of a query.")))),(0,r.yg)("h2",{id:"sourcefield"},"#","[SourceField]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," attribute is used to declare a GraphQL field."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"phpType"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"annotations"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"array\\"),(0,r.yg)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "#',"[Logged]",'" or "#',"[Right]",'" attribute as class here.')))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Note"),": ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,r.yg)("h2",{id:"magicfield"},"#","[MagicField]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[MagicField]")," attribute is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,r.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[ExtendType]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("a",{parentName:"td",href:"/docs/next/custom-types"},"outputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no"),"(*)"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"phpType"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no"),"(*)"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"description"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Field description displayed in the GraphQL docs. If not set, no description will be shown.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"sourceName"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the property in the source class. If not set, the ",(0,r.yg)("inlineCode",{parentName:"td"},"name")," will be used to get property value.")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"annotations"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"array\\"),(0,r.yg)("td",{parentName:"tr",align:null},'A set of annotations that apply to this field. You would typically used a "#',"[Logged]",'" or "#',"[Right]",'" attribute as class here.')))),(0,r.yg)("p",null,"(*) ",(0,r.yg)("strong",{parentName:"p"},"Note"),": ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,r.yg)("h2",{id:"prefetch"},"#","[Prefetch]"),(0,r.yg)("p",null,"Marks field parameter to be used for ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/prefetch-method"},"prefetching"),"."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": parameters of methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"callable"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"callable"),(0,r.yg)("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,r.yg)("h2",{id:"logged"},"#","[Logged]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," attribute is used to declare a Query/Mutation/Field is only visible to logged users."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("p",null,"This attribute allows no arguments."),(0,r.yg)("h2",{id:"right"},"#","[Right]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attribute is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,r.yg)("h2",{id:"failwith"},"#","[FailWith]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," attribute is used to declare a default value to return in the user is not authorized to see a specific\nquery/mutation/subscription/field (according to the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes)."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," and one of ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"value"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"mixed"),(0,r.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,r.yg)("h2",{id:"hideifunauthorized"},"#","[HideIfUnauthorized]"),(0,r.yg)("div",{class:"alert alert--warning"},"This attribute 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,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[HideIfUnauthorized]")," attribute is used to completely hide the query/mutation/subscription/field if the user is not authorized\nto access it (according to the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes)."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," and one of ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Logged]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"#[HideIfUnauthorized]")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," are mutually exclusive."),(0,r.yg)("h2",{id:"injectuser"},"#","[InjectUser]"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[InjectUser]")," attribute to inject an instance of the current user logged in into a parameter of your\nquery/mutation/subscription/field."),(0,r.yg)("p",null,"See ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/authentication-authorization"},"the authentication and authorization page")," for more details."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,r.yg)("h2",{id:"security"},"#","[Security]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute 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,r.yg)("p",null,"See ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/fine-grained-security"},"the fine grained security page")," for more details."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods or properties annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"default")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,r.yg)("h2",{id:"factory"},"#","[Factory]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Factory]")," attribute is used to declare a factory that turns GraphQL input types into objects."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"default"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"bool"),(0,r.yg)("td",{parentName:"tr",align:null},"If ",(0,r.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,r.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,r.yg)("a",{parentName:"td",href:"/docs/next/input-types#declaring-several-input-types-for-the-same-php-class"},"reference this factory using the ",(0,r.yg)("inlineCode",{parentName:"a"},"#[Parameter]")," attribute"),".")))),(0,r.yg)("h2",{id:"useinputtype"},"#","[UseInputType]"),(0,r.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"inputType")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,r.yg)("h2",{id:"decorate"},"#","[Decorate]"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Decorate]")," attribute is used ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/extend-input-type"},"to extend/modify/decorate an input type declared with the ",(0,r.yg)("inlineCode",{parentName:"a"},"#[Factory]")," attribute"),"."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,r.yg)("h2",{id:"autowire"},"#","[Autowire]"),(0,r.yg)("p",null,(0,r.yg)("a",{parentName:"p",href:"/docs/next/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,r.yg)("p",null,"Useful to inject services directly into ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," method arguments."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"identifier")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("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,r.yg)("h2",{id:"hideparameter"},"#","[HideParameter]"),(0,r.yg)("p",null,"Removes ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,r.yg)("h2",{id:"cost"},"#","[Cost]"),(0,r.yg)("p",null,"Sets complexity and multipliers on fields for ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/operation-complexity#static-request-analysis"},"automatic query complexity"),"."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"complexity")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"int"),(0,r.yg)("td",{parentName:"tr",align:null},"Complexity for that field")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"multipliers")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"array\\"),(0,r.yg)("td",{parentName:"tr",align:null},"Names of fields by value of which complexity will be multiplied")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"defaultMultiplier")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"int"),(0,r.yg)("td",{parentName:"tr",align:null},"Default multiplier value if all multipliers are missing/null")))),(0,r.yg)("h2",{id:"validate"},"#","[Validate]"),(0,r.yg)("div",{class:"alert alert--info"},"This attribute is only available in the GraphQLite Laravel package"),(0,r.yg)("p",null,(0,r.yg)("a",{parentName:"p",href:"/docs/next/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Factory]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Decorator]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"rule")),(0,r.yg)("td",{parentName:"tr",align:null},"*yes"),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,r.yg)("p",null,"Sample:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Validate(for: "$email", rule: "email|unique:users")]\n')),(0,r.yg)("h2",{id:"assertion"},"#","[Assertion]"),(0,r.yg)("p",null,(0,r.yg)("a",{parentName:"p",href:"/docs/next/validation"},"Validates a user input"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Assertion]")," attribute is available in the ",(0,r.yg)("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,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Mutation]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Factory]")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Decorator]")," attribute."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"for")),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"yes")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"constraint")),(0,r.yg)("td",{parentName:"tr",align:null},"*yes"),(0,r.yg)("td",{parentName:"tr",align:null},"annotation"),(0,r.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation attributes.")))),(0,r.yg)("h2",{id:"enumtype"},(0,r.yg)("del",{parentName:"h2"},"@EnumType")),(0,r.yg)("p",null,(0,r.yg)("em",{parentName:"p"},"Deprecated: Use ",(0,r.yg)("a",{parentName:"em",href:"https://www.php.net/manual/en/language.types.enumerations.php"},"PHP 8.1's native Enums")," instead with a ",(0,r.yg)("a",{parentName:"em",href:"#type-annotation"},"#[Type]"),".")),(0,r.yg)("p",null,"The ",(0,r.yg)("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,r.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,r.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,r.yg)("table",null,(0,r.yg)("thead",{parentName:"table"},(0,r.yg)("tr",{parentName:"thead"},(0,r.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,r.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,r.yg)("th",{parentName:"tr",align:null},"Type"),(0,r.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,r.yg)("tbody",{parentName:"table"},(0,r.yg)("tr",{parentName:"tbody"},(0,r.yg)("td",{parentName:"tr",align:null},"name"),(0,r.yg)("td",{parentName:"tr",align:null},(0,r.yg)("em",{parentName:"td"},"no")),(0,r.yg)("td",{parentName:"tr",align:null},"string"),(0,r.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b26a5b84.39f17309.js b/assets/js/b26a5b84.a3068e3f.js similarity index 99% rename from assets/js/b26a5b84.39f17309.js rename to assets/js/b26a5b84.a3068e3f.js index ab276d596..091fb6709 100644 --- a/assets/js/b26a5b84.39f17309.js +++ b/assets/js/b26a5b84.a3068e3f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1481],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var a=t(96540),r=t(20053);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.A)(l.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),r=t(96540),l=t(20053),i=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);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.X)(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 g(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,o.W6)(),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.aZ)(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 y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=d(e),[i,o]=(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(!g({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,p.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),m=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const n=e.currentTarget,t=p.indexOf(n),a=u[t].value;a!==o&&(c(n),s(a))},g=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,l.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(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 T(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(n)},e))}},75718:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),i=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function h(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Using ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Let's break this sample:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.yg)("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.yg)("p",null,'Using the "',(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1481],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var a=t(96540),r=t(20053);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.A)(l.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),r=t(96540),l=t(20053),i=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);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.X)(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 g(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,o.W6)(),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.aZ)(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 y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=d(e),[i,o]=(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(!g({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,p.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),m=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const n=e.currentTarget,t=p.indexOf(n),a=u[t].value;a!==o&&(c(n),s(a))},g=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,l.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(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 T(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(n)},e))}},75718:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),i=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function h(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Using ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Let's break this sample:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.yg)("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.yg)("p",null,'Using the "',(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b2d9540a.5ed5cc8c.js b/assets/js/b2d9540a.2e9ca6f7.js similarity index 99% rename from assets/js/b2d9540a.5ed5cc8c.js rename to assets/js/b2d9540a.2e9ca6f7.js index dace15b40..f0f5bf5a1 100644 --- a/assets/js/b2d9540a.5ed5cc8c.js +++ b/assets/js/b2d9540a.2e9ca6f7.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1084],{19365:(e,a,t)=>{t.d(a,{A:()=>r});var n=t(96540),i=t(20053);const o={tabItem:"tabItem_Ymn6"};function r(e){let{children:a,hidden:t,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,i.A)(o.tabItem,r),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>N});var n=t(58168),i=t(96540),o=t(20053),r=t(23104),l=t(56347),s=t(57485),u=t(31682),d=t(89466);function p(e){return function(e){return i.Children.map(e,(e=>{if(!e||(0,i.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:i}}=e;return{value:a,label:t,attributes:n,default:i}}))}function c(e){const{values:a,children:t}=e;return(0,i.useMemo)((()=>{const e=a??p(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function y(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:t}=e;const n=(0,l.W6)(),o=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(o),(0,i.useCallback)((e=>{if(!o)return;const a=new URLSearchParams(n.location.search);a.set(o,e),n.replace({...n.location,search:a.toString()})}),[o,n])]}function m(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,o=c(e),[r,l]=(0,i.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!y({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:o}))),[s,u]=h({queryString:t,groupId:n}),[p,m]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,o]=(0,d.Dv)(t);return[n,(0,i.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:n}),g=(()=>{const e=s??p;return y({value:e,tabValues:o})?e:null})();(0,i.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!y({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),m(e)}),[u,m,o]),tabValues:o}}var g=t(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:a,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),c=e=>{const a=e.currentTarget,t=d.indexOf(a),n=u[t].value;n!==l&&(p(a),s(n))},y=e=>{let a=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const t=d.indexOf(e.currentTarget)+1;a=d[t]??d[0];break}case"ArrowLeft":{const t=d.indexOf(e.currentTarget)-1;a=d[t]??d[d.length-1];break}}a?.focus()};return i.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:r}=e;return i.createElement("li",(0,n.A)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:e=>d.push(e),onKeyDown:y,onClick:c},r,{className:(0,o.A)("tabs__item",v.tabItem,r?.className,{"tabs__item--active":l===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,i.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=m(e);return i.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},i.createElement(f,(0,n.A)({},e,a)),i.createElement(b,(0,n.A)({},e,a)))}function N(e){const a=(0,g.A)();return i.createElement(w,(0,n.A)({key:String(a)},e))}},90837:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=t(58168),i=(t(96540),t(15680)),o=(t(67443),t(11470)),r=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:a,...t}=e;return(0,i.yg)(y,(0,n.A)({},c,t,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.yg)("pre",{parentName:"li"},(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,i.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,i.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.yg)("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.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.yg)("p",null,"You can also pass an array to the ",(0,i.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,i.yg)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"),(0,i.yg)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.yg)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.yg)("inlineCode",{parentName:"p"},"@Input")," annotation or PHP8 ",(0,i.yg)("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.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("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.yg)("p",null,"To get started with validation on input types defined by an ",(0,i.yg)("inlineCode",{parentName:"p"},"@Input")," annotation, you'll first need to register your validator with the ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Your input type validator must implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.yg)("p",null,"You'll notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.yg)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.yg)("p",null,"Also available is the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1084],{19365:(e,a,t)=>{t.d(a,{A:()=>r});var n=t(96540),i=t(20053);const o={tabItem:"tabItem_Ymn6"};function r(e){let{children:a,hidden:t,className:r}=e;return n.createElement("div",{role:"tabpanel",className:(0,i.A)(o.tabItem,r),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>N});var n=t(58168),i=t(96540),o=t(20053),r=t(23104),l=t(56347),s=t(57485),u=t(31682),d=t(89466);function p(e){return function(e){return i.Children.map(e,(e=>{if(!e||(0,i.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:i}}=e;return{value:a,label:t,attributes:n,default:i}}))}function c(e){const{values:a,children:t}=e;return(0,i.useMemo)((()=>{const e=a??p(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function y(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:t}=e;const n=(0,l.W6)(),o=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(o),(0,i.useCallback)((e=>{if(!o)return;const a=new URLSearchParams(n.location.search);a.set(o,e),n.replace({...n.location,search:a.toString()})}),[o,n])]}function m(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,o=c(e),[r,l]=(0,i.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!y({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:o}))),[s,u]=h({queryString:t,groupId:n}),[p,m]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,o]=(0,d.Dv)(t);return[n,(0,i.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:n}),g=(()=>{const e=s??p;return y({value:e,tabValues:o})?e:null})();(0,i.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!y({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),m(e)}),[u,m,o]),tabValues:o}}var g=t(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:a,block:t,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),c=e=>{const a=e.currentTarget,t=d.indexOf(a),n=u[t].value;n!==l&&(p(a),s(n))},y=e=>{let a=null;switch(e.key){case"Enter":c(e);break;case"ArrowRight":{const t=d.indexOf(e.currentTarget)+1;a=d[t]??d[0];break}case"ArrowLeft":{const t=d.indexOf(e.currentTarget)-1;a=d[t]??d[d.length-1];break}}a?.focus()};return i.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:r}=e;return i.createElement("li",(0,n.A)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:e=>d.push(e),onKeyDown:y,onClick:c},r,{className:(0,o.A)("tabs__item",v.tabItem,r?.className,{"tabs__item--active":l===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,i.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=m(e);return i.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},i.createElement(f,(0,n.A)({},e,a)),i.createElement(b,(0,n.A)({},e,a)))}function N(e){const a=(0,g.A)();return i.createElement(w,(0,n.A)({key:String(a)},e))}},90837:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>d,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var n=t(58168),i=(t(96540),t(15680)),o=(t(67443),t(11470)),r=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:a,...t}=e;return(0,i.yg)(y,(0,n.A)({},c,t,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.yg)("pre",{parentName:"li"},(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,i.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,i.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,i.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.yg)("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.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.yg)("p",null,"You can also pass an array to the ",(0,i.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,i.yg)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"),(0,i.yg)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.yg)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.yg)("inlineCode",{parentName:"p"},"@Input")," annotation or PHP8 ",(0,i.yg)("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.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("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.yg)("p",null,"To get started with validation on input types defined by an ",(0,i.yg)("inlineCode",{parentName:"p"},"@Input")," annotation, you'll first need to register your validator with the ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Your input type validator must implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.yg)("p",null,"You'll notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.yg)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.yg)("p",null,"Also available is the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b35d1284.a50b0cce.js b/assets/js/b35d1284.8a45607f.js similarity index 98% rename from assets/js/b35d1284.a50b0cce.js rename to assets/js/b35d1284.8a45607f.js index 59ef0cd25..f8e0694e4 100644 --- a/assets/js/b35d1284.a50b0cce.js +++ b/assets/js/b35d1284.8a45607f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[552],{49395:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/5.0/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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([[552],{49395:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/5.0/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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.36f5b217.js b/assets/js/b370b50c.3d779569.js similarity index 99% rename from assets/js/b370b50c.36f5b217.js rename to assets/js/b370b50c.3d779569.js index af7d7cc01..a30c09718 100644 --- a/assets/js/b370b50c.36f5b217.js +++ b/assets/js/b370b50c.3d779569.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5747],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),g(e)}),[u,g,i]),tabValues:i}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function T(e){const t=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},31332:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),i=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(h,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null," #[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null," #[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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([[5747],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),g(e)}),[u,g,i]),tabValues:i}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function T(e){const t=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},31332:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),i=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(h,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null," #[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null," #[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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.2af07bda.js b/assets/js/b42f5805.7f5efebe.js similarity index 99% rename from assets/js/b42f5805.2af07bda.js rename to assets/js/b42f5805.7f5efebe.js index e3831cad6..0d9efb4c1 100644 --- a/assets/js/b42f5805.2af07bda.js +++ b/assets/js/b42f5805.7f5efebe.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6427],{19365:(e,n,t)=>{t.d(n,{A:()=>r});var a=t(96540),o=t(20053);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.A)(i.tabItem,r),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>A});var a=t(58168),o=t(96540),i=t(20053),r=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.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:o}}=e;return{value:n,label:t,attributes:a,default:o}}))}function d(e){const{values:n,children:t}=e;return(0,o.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 y(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,l.W6)(),i=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.aZ)(i),(0,o.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.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(!y({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:i}))),[u,s]=h({queryString:t,groupId:a}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,o.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),m=(()=>{const e=u??p;return y({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{m&&l(m)}),[m]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!y({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(p(n),u(a))},y=e=>{let n=null;switch(e.key){case"Enter":d(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 o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:r}=e;return o.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:y,onClick:d},r,{className:(0,i.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===n})}),t??n)})))}function T(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,o.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=g(e);return o.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},o.createElement(b,(0,a.A)({},e,n)),o.createElement(T,(0,a.A)({},e,n)))}function A(e){const n=(0,m.A)();return o.createElement(v,(0,a.A)({key:String(n)},e))}},15726:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>h,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=t(58168),o=(t(96540),t(15680)),i=(t(67443),t(11470)),r=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:n,...t}=e;return(0,o.yg)(y,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.yg)("p",null,"For instance:"),(0,o.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,o.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.yg)("p",null,"GraphQLite allows you to use a ",(0,o.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!")," The ",(0,o.yg)("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.yg)("br",null),(0,o.yg)("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.yg)("p",null,"In methods with a ",(0,o.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.yg)("h2",{id:"sourcefield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.yg)("p",null,"If you don't want to rewrite all ",(0,o.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.yg)("h2",{id:"magicfield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"Any annotations described in the ",(0,o.yg)("a",{parentName:"p",href:"/docs/4.3/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/4.3/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.yg)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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")))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6427],{19365:(e,n,t)=>{t.d(n,{A:()=>r});var a=t(96540),o=t(20053);const i={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:t,className:r}=e;return a.createElement("div",{role:"tabpanel",className:(0,o.A)(i.tabItem,r),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>A});var a=t(58168),o=t(96540),i=t(20053),r=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function p(e){return function(e){return o.Children.map(e,(e=>{if(!e||(0,o.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:o}}=e;return{value:n,label:t,attributes:a,default:o}}))}function d(e){const{values:n,children:t}=e;return(0,o.useMemo)((()=>{const e=n??p(t);return function(e){const n=(0,s.X)(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 y(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,l.W6)(),i=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.aZ)(i),(0,o.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function g(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=d(e),[r,l]=(0,o.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(!y({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:i}))),[u,s]=h({queryString:t,groupId:a}),[p,g]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,o.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),m=(()=>{const e=u??p;return y({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{m&&l(m)}),[m]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!y({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),d=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(p(n),u(a))},y=e=>{let n=null;switch(e.key){case"Enter":d(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 o.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:r}=e;return o.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:y,onClick:d},r,{className:(0,i.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===n})}),t??n)})))}function T(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,o.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function v(e){const n=g(e);return o.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},o.createElement(b,(0,a.A)({},e,n)),o.createElement(T,(0,a.A)({},e,n)))}function A(e){const n=(0,m.A)();return o.createElement(v,(0,a.A)({key:String(n)},e))}},15726:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>h,frontMatter:()=>l,metadata:()=>s,toc:()=>p});var a=t(58168),o=(t(96540),t(15680)),i=(t(67443),t(11470)),r=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:n,...t}=e;return(0,o.yg)(y,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.yg)("p",null,"For instance:"),(0,o.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,o.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.yg)("p",null,"GraphQLite allows you to use a ",(0,o.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!")," The ",(0,o.yg)("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.yg)("br",null),(0,o.yg)("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.yg)("p",null,"In methods with a ",(0,o.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.yg)("h2",{id:"sourcefield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.yg)("p",null,"If you don't want to rewrite all ",(0,o.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"isName()"),")."),(0,o.yg)("h2",{id:"magicfield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"Any annotations described in the ",(0,o.yg)("a",{parentName:"p",href:"/docs/4.3/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/4.3/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.yg)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,o.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,o.yg)("pre",null,(0,o.yg)("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")))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b4657038.3d7bc7ef.js b/assets/js/b4657038.7c76f1b3.js similarity index 98% rename from assets/js/b4657038.3d7bc7ef.js rename to assets/js/b4657038.7c76f1b3.js index 113d18edb..5ea3e3ac8 100644 --- a/assets/js/b4657038.3d7bc7ef.js +++ b/assets/js/b4657038.7c76f1b3.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1886],{94936:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},c="wrapper";function d(t){let{components:e,...n}=t;return(0,i.yg)(c,(0,a.A)({},u,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in GraphQLite 5.0"),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,i.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"Please note that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,i.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,i.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,i.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,i.yg)("div",{class:"alert alert--info"},(0,i.yg)("strong",null,"Heads up!"),"Some IDEs provide support for Doctrine annotations:",(0,i.yg)("ul",null,(0,i.yg)("li",null,"PhpStorm via the ",(0,i.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,i.yg)("li",null,"Eclipse via the ",(0,i.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,i.yg)("li",null,"Netbeans has native support")),(0,i.yg)("p",null,"We strongly recommend using an IDE that has Doctrine annotations support.")),(0,i.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.yg)("p",null,"The same code can be written this way:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.yg)("p",null,"They support the same attributes too."),(0,i.yg)("p",null,"A few notable differences:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,i.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,i.yg)("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.yg)("p",null,"Let's take an example with the ",(0,i.yg)("a",{parentName:"p",href:"/docs/3.0/autowiring"},(0,i.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"PHP 7+")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"PHP 8")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1886],{94936:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},c="wrapper";function d(t){let{components:e,...n}=t;return(0,i.yg)(c,(0,a.A)({},u,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in GraphQLite 5.0"),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,i.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"Please note that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,i.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,i.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,i.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,i.yg)("div",{class:"alert alert--info"},(0,i.yg)("strong",null,"Heads up!"),"Some IDEs provide support for Doctrine annotations:",(0,i.yg)("ul",null,(0,i.yg)("li",null,"PhpStorm via the ",(0,i.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,i.yg)("li",null,"Eclipse via the ",(0,i.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,i.yg)("li",null,"Netbeans has native support")),(0,i.yg)("p",null,"We strongly recommend using an IDE that has Doctrine annotations support.")),(0,i.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.yg)("p",null,"The same code can be written this way:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.yg)("p",null,"They support the same attributes too."),(0,i.yg)("p",null,"A few notable differences:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,i.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,i.yg)("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.yg)("p",null,"Let's take an example with the ",(0,i.yg)("a",{parentName:"p",href:"/docs/3.0/autowiring"},(0,i.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"PHP 7+")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"PHP 8")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b4aea2ce.968ca243.js b/assets/js/b4aea2ce.28ba2067.js similarity index 98% rename from assets/js/b4aea2ce.968ca243.js rename to assets/js/b4aea2ce.28ba2067.js index ef73b96a9..d997b5ac4 100644 --- a/assets/js/b4aea2ce.968ca243.js +++ b/assets/js/b4aea2ce.28ba2067.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5138],{68781:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>i,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var r=n(58168),t=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function c(e){let{components:a,...n}=e;return(0,t.yg)(g,(0,r.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,t.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,t.yg)("strong",{parentName:"p"},"Laravel 5.x"),"."),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,t.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,t.yg)("p",null,"You can then configure the library by editing ",(0,t.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/graphqlite.php")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => '/graphql'\n];\n")),(0,t.yg)("p",null,"The debug parameters are detailed in the ",(0,t.yg)("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,t.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,t.yg)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,t.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5138],{68781:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>i,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var r=n(58168),t=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function c(e){let{components:a,...n}=e;return(0,t.yg)(g,(0,r.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,t.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,t.yg)("strong",{parentName:"p"},"Laravel 5.x"),"."),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,t.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,t.yg)("p",null,"You can then configure the library by editing ",(0,t.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/graphqlite.php")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"}," 'App\\\\Http\\\\Controllers',\n 'types' => 'App\\\\',\n 'debug' => Debug::RETHROW_UNSAFE_EXCEPTIONS,\n 'uri' => '/graphql'\n];\n")),(0,t.yg)("p",null,"The debug parameters are detailed in the ",(0,t.yg)("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,t.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,t.yg)("p",null,"You can also use any external client with GraphQLite, make sure to point it to the URL defined in the config (",(0,t.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b5d0ac54.3aa583e2.js b/assets/js/b5d0ac54.f18e7f3c.js similarity index 99% rename from assets/js/b5d0ac54.3aa583e2.js rename to assets/js/b5d0ac54.f18e7f3c.js index 6eac1b417..3b2f11e80 100644 --- a/assets/js/b5d0ac54.3aa583e2.js +++ b/assets/js/b5d0ac54.f18e7f3c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3343],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var t=a(96540),r=a(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),l=a(20053),i=a(23104),s=a(56347),p=a(57485),c=a(31682),o=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function m(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function d(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function y(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[p,c]=g({queryString:a,groupId:t}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{h&&s(h)}),[h]);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),y(e)}),[c,y,l]),tabValues:l}}var h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=c[a].value;t!==s&&(u(n),p(t))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return r.createElement("li",(0,t.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function N(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(v,(0,t.A)({},e,n)))}function T(e){const n=(0,h.A)();return r.createElement(N,(0,t.A)({key:String(n)},e))}},15753:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>g,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var t=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...a}=e;return(0,r.yg)(d,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.yg)("p",null,"Written in ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.yg)("p",null,"The GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.yg)("p",null,"This will translate in GraphQL schema as:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.yg)("p",null,"Please note that you do not need to put the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.yg)("p",null,"You don't have to explicitly put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3343],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var t=a(96540),r=a(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),l=a(20053),i=a(23104),s=a(56347),p=a(57485),c=a(31682),o=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function m(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function d(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function y(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[p,c]=g({queryString:a,groupId:t}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{h&&s(h)}),[h]);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),y(e)}),[c,y,l]),tabValues:l}}var h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=c[a].value;t!==s&&(u(n),p(t))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return r.createElement("li",(0,t.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function N(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(v,(0,t.A)({},e,n)))}function T(e){const n=(0,h.A)();return r.createElement(N,(0,t.A)({key:String(n)},e))}},15753:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>g,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var t=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...a}=e;return(0,r.yg)(d,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.yg)("p",null,"Written in ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.yg)("p",null,"The GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.yg)("p",null,"This will translate in GraphQL schema as:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.yg)("p",null,"Please note that you do not need to put the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.yg)("p",null,"You don't have to explicitly put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b5d32d98.83d31ffc.js b/assets/js/b5d32d98.f05b0f6c.js similarity index 98% rename from assets/js/b5d32d98.83d31ffc.js rename to assets/js/b5d32d98.f05b0f6c.js index c13324d4a..7e75d544d 100644 --- a/assets/js/b5d32d98.83d31ffc.js +++ b/assets/js/b5d32d98.f05b0f6c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[481],{62062:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>n,metadata:()=>r,toc:()=>p});var o=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,i.yg)(d,(0,o.A)({},u,t,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,i.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,i.yg)("h2",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,i.yg)("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.yg)("h2",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,i.yg)("p",null,"In order to use this, you must first be sure that the ",(0,i.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,i.yg)("p",null,"Simply add ",(0,i.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,i.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,i.yg)("h2",{id:"usage"},"Usage"),(0,i.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,i.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests."),(0,i.yg)("p",null,"See ",(0,i.yg)("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([[481],{62062:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>n,metadata:()=>r,toc:()=>p});var o=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,i.yg)(d,(0,o.A)({},u,t,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,i.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,i.yg)("h2",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,i.yg)("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.yg)("h2",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,i.yg)("p",null,"In order to use this, you must first be sure that the ",(0,i.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,i.yg)("p",null,"Simply add ",(0,i.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,i.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,i.yg)("h2",{id:"usage"},"Usage"),(0,i.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,i.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests."),(0,i.yg)("p",null,"See ",(0,i.yg)("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/b6722b03.4c0cf4e3.js b/assets/js/b6722b03.72cf7e0e.js similarity index 99% rename from assets/js/b6722b03.4c0cf4e3.js rename to assets/js/b6722b03.72cf7e0e.js index 63cc8d720..192dbe32f 100644 --- a/assets/js/b6722b03.4c0cf4e3.js +++ b/assets/js/b6722b03.72cf7e0e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[663],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(l.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),l=a(20053),u=a(23104),o=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.W6)(),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.aZ)(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 h(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]=g({queryString:a,groupId:n}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);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),h(e)}),[i,h,l]),tabValues:l}}var b=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.tabItem,u?.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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(f,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function T(e){const t=(0,b.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},70259:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),u=a(19365);const o={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},s=void 0,i={unversionedId:"index",id:"version-7.0.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-7.0.0/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/7.0.0/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/README.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/7.0.0/getting-started"}},c={},p=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, subscriptions, mapping of arrays / iterators,\nfile uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[663],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(l.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),l=a(20053),u=a(23104),o=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.W6)(),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.aZ)(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 h(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]=g({queryString:a,groupId:n}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);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),h(e)}),[i,h,l]),tabValues:l}}var b=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.tabItem,u?.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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(f,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function T(e){const t=(0,b.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},70259:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),u=a(19365);const o={id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},s=void 0,i={unversionedId:"index",id:"version-7.0.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-7.0.0/README.mdx",sourceDirName:".",slug:"/",permalink:"/docs/7.0.0/",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/README.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/7.0.0/getting-started"}},c={},p=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, subscriptions, mapping of arrays / iterators,\nfile uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b69ed219.14a7f32f.js b/assets/js/b69ed219.fb526318.js similarity index 99% rename from assets/js/b69ed219.14a7f32f.js rename to assets/js/b69ed219.fb526318.js index b24fbd841..263b47fbb 100644 --- a/assets/js/b69ed219.14a7f32f.js +++ b/assets/js/b69ed219.fb526318.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2089],{53052:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>g,frontMatter:()=>r,metadata:()=>s,toc:()=>l});var i=n(58168),a=(n(96540),n(15680));n(67443);const r={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},o=void 0,s={unversionedId:"authentication-authorization",id:"version-8.0.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",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/authentication-authorization.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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] attributes",id:"logged-and-right-attributes",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 / subscriptions",id:"hiding-fields--queries--mutations--subscriptions",level:2}],d={toc:l},h="wrapper";function g(e){let{components:t,...n}=e;return(0,a.yg)(h,(0,i.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some\nqueries/mutations/subscriptions or fields reserved to some users."),(0,a.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to\nresources:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,a.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,a.yg)("inlineCode",{parentName:"a"},"#[Logged]")," attribute")," (restrict access to logged users)"),(0,a.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,a.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,a.yg)("inlineCode",{parentName:"a"},"#[Right]")," attribute")," (restrict access to logged users with certain rights)."),(0,a.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,a.yg)("a",{parentName:"li",href:"/docs/fine-grained-security"},(0,a.yg)("inlineCode",{parentName:"a"},"#[Security]")," attribute")," (restrict access for some given resources to some users).")),(0,a.yg)("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,a.yg)("br",null),"See ",(0,a.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,a.yg)("h2",{id:"logged-and-right-attributes"},(0,a.yg)("inlineCode",{parentName:"h2"},"#[Logged]")," and ",(0,a.yg)("inlineCode",{parentName:"h2"},"#[Right]")," attributes"),(0,a.yg)("p",null,"GraphQLite exposes two attributes (",(0,a.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Right]"),") that you can use to restrict access to a resource."),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("p",null,"In the example above, the query ",(0,a.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,a.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,a.yg)("p",null,(0,a.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes can be used next to:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("inlineCode",{parentName:"li"},"#[Query]")," attributes"),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("inlineCode",{parentName:"li"},"#[Mutation]")," attributes"),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("inlineCode",{parentName:"li"},"#[Field]")," attributes")),(0,a.yg)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/subscription/field, an error is raised and the query fails."),(0,a.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,a.yg)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation/subscription\nthey have no access to, you can use the ",(0,a.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," attribute."),(0,a.yg)("p",null,"The ",(0,a.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," attribute contains the value that will be returned for users with insufficient rights."),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,a.yg)("p",null,"Use the ",(0,a.yg)("inlineCode",{parentName:"p"},"#[InjectUser]")," attribute to get an instance of the current user logged in."),(0,a.yg)("pre",null,(0,a.yg)("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 * @return Product\n */\n #[Query]\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n")),(0,a.yg)("p",null,"The ",(0,a.yg)("inlineCode",{parentName:"p"},"#[InjectUser]")," attribute can be used next to:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("inlineCode",{parentName:"li"},"#[Query]")," attributes"),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("inlineCode",{parentName:"li"},"#[Mutation]")," attributes"),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("inlineCode",{parentName:"li"},"#[Field]")," attributes")),(0,a.yg)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,a.yg)("a",{parentName:"p",href:"/docs/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,a.yg)("inlineCode",{parentName:"p"},"#[Logged]")," attribute."),(0,a.yg)("h2",{id:"hiding-fields--queries--mutations--subscriptions"},"Hiding fields / queries / mutations / subscriptions"),(0,a.yg)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/subscriptions/types available.\nSome will be available to him and some won't."),(0,a.yg)("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,a.yg)("inlineCode",{parentName:"p"},"#[HideIfUnauthorized]")," attribute. Beware of ",(0,a.yg)("a",{parentName:"p",href:"/docs/annotations-reference"},"it's limitations"),"."),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("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,a.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optional from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2089],{53052:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>g,frontMatter:()=>r,metadata:()=>s,toc:()=>l});var i=n(58168),a=(n(96540),n(15680));n(67443);const r={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},o=void 0,s={unversionedId:"authentication-authorization",id:"version-8.0.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",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/authentication-authorization.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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] attributes",id:"logged-and-right-attributes",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 / subscriptions",id:"hiding-fields--queries--mutations--subscriptions",level:2}],d={toc:l},h="wrapper";function g(e){let{components:t,...n}=e;return(0,a.yg)(h,(0,i.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some\nqueries/mutations/subscriptions or fields reserved to some users."),(0,a.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to\nresources:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,a.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,a.yg)("inlineCode",{parentName:"a"},"#[Logged]")," attribute")," (restrict access to logged users)"),(0,a.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,a.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,a.yg)("inlineCode",{parentName:"a"},"#[Right]")," attribute")," (restrict access to logged users with certain rights)."),(0,a.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,a.yg)("a",{parentName:"li",href:"/docs/fine-grained-security"},(0,a.yg)("inlineCode",{parentName:"a"},"#[Security]")," attribute")," (restrict access for some given resources to some users).")),(0,a.yg)("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,a.yg)("br",null),"See ",(0,a.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,a.yg)("h2",{id:"logged-and-right-attributes"},(0,a.yg)("inlineCode",{parentName:"h2"},"#[Logged]")," and ",(0,a.yg)("inlineCode",{parentName:"h2"},"#[Right]")," attributes"),(0,a.yg)("p",null,"GraphQLite exposes two attributes (",(0,a.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Right]"),") that you can use to restrict access to a resource."),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("p",null,"In the example above, the query ",(0,a.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,a.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,a.yg)("p",null,(0,a.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,a.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes can be used next to:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("inlineCode",{parentName:"li"},"#[Query]")," attributes"),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("inlineCode",{parentName:"li"},"#[Mutation]")," attributes"),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("inlineCode",{parentName:"li"},"#[Field]")," attributes")),(0,a.yg)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/subscription/field, an error is raised and the query fails."),(0,a.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,a.yg)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation/subscription\nthey have no access to, you can use the ",(0,a.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," attribute."),(0,a.yg)("p",null,"The ",(0,a.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," attribute contains the value that will be returned for users with insufficient rights."),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,a.yg)("p",null,"Use the ",(0,a.yg)("inlineCode",{parentName:"p"},"#[InjectUser]")," attribute to get an instance of the current user logged in."),(0,a.yg)("pre",null,(0,a.yg)("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 * @return Product\n */\n #[Query]\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n")),(0,a.yg)("p",null,"The ",(0,a.yg)("inlineCode",{parentName:"p"},"#[InjectUser]")," attribute can be used next to:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("inlineCode",{parentName:"li"},"#[Query]")," attributes"),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("inlineCode",{parentName:"li"},"#[Mutation]")," attributes"),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("inlineCode",{parentName:"li"},"#[Field]")," attributes")),(0,a.yg)("p",null,"The object injected as the current user depends on your framework. It is in fact the object returned by the\n",(0,a.yg)("a",{parentName:"p",href:"/docs/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,a.yg)("inlineCode",{parentName:"p"},"#[Logged]")," attribute."),(0,a.yg)("h2",{id:"hiding-fields--queries--mutations--subscriptions"},"Hiding fields / queries / mutations / subscriptions"),(0,a.yg)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/subscriptions/types available.\nSome will be available to him and some won't."),(0,a.yg)("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,a.yg)("inlineCode",{parentName:"p"},"#[HideIfUnauthorized]")," attribute. Beware of ",(0,a.yg)("a",{parentName:"p",href:"/docs/annotations-reference"},"it's limitations"),"."),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("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,a.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optional from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b6a6a31f.3168611a.js b/assets/js/b6a6a31f.c449286c.js similarity index 98% rename from assets/js/b6a6a31f.3168611a.js rename to assets/js/b6a6a31f.c449286c.js index f72677c15..a2e66043d 100644 --- a/assets/js/b6a6a31f.3168611a.js +++ b/assets/js/b6a6a31f.c449286c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4955],{65995:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>i,default:()=>d,frontMatter:()=>s,metadata:()=>o,toc:()=>h});var a=n(58168),r=(n(96540),n(15680));n(67443);const s={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,o={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},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},c="wrapper";function d(e){let{components:t,...n}=e;return(0,r.yg)(c,(0,a.A)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/next/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When a ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Prefetch]")," attribute is detected on a parameter of ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute, the method is called automatically.\nThe prefetch callable must be one of the following:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a static method in the same class: ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Prefetch('prefetchMethod')]")),(0,r.yg)("li",{parentName:"ul"},"a static method in a different class: ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Prefetch([OtherClass::class, 'prefetchMethod')]")),(0,r.yg)("li",{parentName:"ul"},"a non-static method in a different class, resolvable through the container: ",(0,r.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," annotated method OR/AND on the prefetch methods."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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')))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4955],{65995:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>i,default:()=>d,frontMatter:()=>s,metadata:()=>o,toc:()=>h});var a=n(58168),r=(n(96540),n(15680));n(67443);const s={id:"prefetch-method",title:"Prefetching records",sidebar_label:"Prefetching records"},i=void 0,o={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},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},c="wrapper";function d(e){let{components:t,...n}=e;return(0,r.yg)(c,(0,a.A)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/next/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When a ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Prefetch]")," attribute is detected on a parameter of ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute, the method is called automatically.\nThe prefetch callable must be one of the following:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a static method in the same class: ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Prefetch('prefetchMethod')]")),(0,r.yg)("li",{parentName:"ul"},"a static method in a different class: ",(0,r.yg)("inlineCode",{parentName:"li"},"#[Prefetch([OtherClass::class, 'prefetchMethod')]")),(0,r.yg)("li",{parentName:"ul"},"a non-static method in a different class, resolvable through the container: ",(0,r.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," annotated method OR/AND on the prefetch methods."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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')))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b7442939.ac73da7f.js b/assets/js/b7442939.e9f19ed1.js similarity index 99% rename from assets/js/b7442939.ac73da7f.js rename to assets/js/b7442939.e9f19ed1.js index ce61f23c2..27c875ba5 100644 --- a/assets/js/b7442939.ac73da7f.js +++ b/assets/js/b7442939.e9f19ed1.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3781],{5488:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},m,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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([[3781],{5488:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},m,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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/b8487569.bdbe52f0.js b/assets/js/b8487569.6f9d53c5.js similarity index 99% rename from assets/js/b8487569.bdbe52f0.js rename to assets/js/b8487569.6f9d53c5.js index e5026ee11..8a7bbaab1 100644 --- a/assets/js/b8487569.bdbe52f0.js +++ b/assets/js/b8487569.6f9d53c5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8526],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var a=t(96540),r=t(20053);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.A)(l.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),r=t(96540),l=t(20053),i=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);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.X)(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 g(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,o.W6)(),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.aZ)(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 y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=d(e),[i,o]=(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(!g({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,p.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),m=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const n=e.currentTarget,t=p.indexOf(n),a=u[t].value;a!==o&&(c(n),s(a))},g=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,l.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(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 T(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(n)},e))}},68838:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),i=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function h(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Using ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Let's break this sample:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.yg)("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.yg)("p",null,'Using the "',(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8526],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var a=t(96540),r=t(20053);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.A)(l.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),r=t(96540),l=t(20053),i=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);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.X)(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 g(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,o.W6)(),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.aZ)(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 y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=d(e),[i,o]=(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(!g({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,p.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),m=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const n=e.currentTarget,t=p.indexOf(n),a=u[t].value;a!==o&&(c(n),s(a))},g=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,l.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(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 T(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(n)},e))}},68838:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),i=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function h(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Using ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Let's break this sample:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.yg)("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.yg)("p",null,'Using the "',(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b94a1068.3c6fd15a.js b/assets/js/b94a1068.d4092ec3.js similarity index 99% rename from assets/js/b94a1068.3c6fd15a.js rename to assets/js/b94a1068.d4092ec3.js index 0de0b2808..50804a56f 100644 --- a/assets/js/b94a1068.3c6fd15a.js +++ b/assets/js/b94a1068.d4092ec3.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6628],{17723:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>l,default:()=>d,frontMatter:()=>r,metadata:()=>s,toc:()=>c});var t=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:n,...a}=e;return(0,i.yg)(g,(0,t.A)({},o,a,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,i.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.yg)("p",null,"Written in ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.yg)("p",null,"The GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,i.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,i.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.yg)("p",null,"This will translate in GraphQL schema as:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,i.yg)("p",null,"Please note that you do not need to put the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,i.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,i.yg)("p",null,"You don't have to explicitly put a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,i.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6628],{17723:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>l,default:()=>d,frontMatter:()=>r,metadata:()=>s,toc:()=>c});var t=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:n,...a}=e;return(0,i.yg)(g,(0,t.A)({},o,a,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,i.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.yg)("p",null,"Written in ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.yg)("p",null,"The GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,i.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,i.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.yg)("p",null,"This will translate in GraphQL schema as:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,i.yg)("p",null,"Please note that you do not need to put the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,i.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,i.yg)("p",null,"You don't have to explicitly put a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,i.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b9d6d6e5.1e186d4a.js b/assets/js/b9d6d6e5.7eec6184.js similarity index 98% rename from assets/js/b9d6d6e5.1e186d4a.js rename to assets/js/b9d6d6e5.7eec6184.js index 5c9cc99f8..e3da71e0b 100644 --- a/assets/js/b9d6d6e5.1e186d4a.js +++ b/assets/js/b9d6d6e5.7eec6184.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8542],{72906:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>p,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},g=[{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],d={toc:g},u="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(u,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/4.0/annotations_reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8542],{72906:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>p,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},g=[{value:"Migrating from v3.0 to v4.0",id:"migrating-from-v30-to-v40",level:2}],d={toc:g},u="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(u,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/4.0/annotations_reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b9ea999a.871dcece.js b/assets/js/b9ea999a.bd76e3cd.js similarity index 99% rename from assets/js/b9ea999a.871dcece.js rename to assets/js/b9ea999a.bd76e3cd.js index 95f1e0aea..7b65e1dbb 100644 --- a/assets/js/b9ea999a.871dcece.js +++ b/assets/js/b9ea999a.bd76e3cd.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2830],{16295:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var n=a(58168),l=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},g={},p=[{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}],y={toc:p},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.yg)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.yg)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("a",{parentName:"td",href:"/docs/4.1/external_type_declaration"},"the class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("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.yg)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/4.1/extend_type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"value"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("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.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/extend_input_type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2830],{16295:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var n=a(58168),l=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},g={},p=[{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}],y={toc:p},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Note: all annotations are available both in a Doctrine annotation format (",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),") and in PHP 8 attribute format (",(0,l.yg)("inlineCode",{parentName:"p"},"#[Query]"),").\nSee ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/doctrine-annotations-attributes"},"Doctrine annotations vs PHP 8 attributes")," for more details."),(0,l.yg)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("a",{parentName:"td",href:"/docs/4.1/external_type_declaration"},"the class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("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.yg)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/4.1/extend_type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.1/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"value"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("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.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/extend_input_type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.1/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/ba7653ad.1fba9352.js b/assets/js/ba7653ad.201e2661.js similarity index 99% rename from assets/js/ba7653ad.1fba9352.js rename to assets/js/ba7653ad.201e2661.js index 81576bf46..3099e35a1 100644 --- a/assets/js/ba7653ad.1fba9352.js +++ b/assets/js/ba7653ad.201e2661.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4716],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),u=a(56347),i=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),g=(()=>{const e=i??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&u(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}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var g=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},14912:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},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.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.yg)("p",null,"You must start by installing this package:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.yg)("p",null,"In order to use this, you must first be sure that the ",(0,r.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.yg)("pre",null,(0,r.yg)("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([[4716],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),u=a(56347),i=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),g=(()=>{const e=i??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&u(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}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var g=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},14912:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},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.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.yg)("p",null,"You must start by installing this package:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.yg)("p",null,"In order to use this, you must first be sure that the ",(0,r.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.yg)("pre",null,(0,r.yg)("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.9dc60367.js b/assets/js/bb5ef1b7.9bb649c8.js similarity index 99% rename from assets/js/bb5ef1b7.9dc60367.js rename to assets/js/bb5ef1b7.9bb649c8.js index 749eb2912..11b5bfb3b 100644 --- a/assets/js/bb5ef1b7.9dc60367.js +++ b/assets/js/bb5ef1b7.9bb649c8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[651],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),g(e)}),[u,g,i]),tabValues:i}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function T(e){const t=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},35575:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),i=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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,...a}=e;return(0,r.yg)(h,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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([[651],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(i.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),i=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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,g]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,i]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&i.set(e)}),[a,i])]}({groupId:n}),y=(()=>{const e=s??d;return h({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),g(e)}),[u,g,i]),tabValues:i}}var y=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===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 w(e){const t=g(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,t)),r.createElement(b,(0,n.A)({},e,t)))}function T(e){const t=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},35575:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),i=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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,...a}=e;return(0,r.yg)(h,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,r.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,r.yg)("p",null,"Most of the time, your ",(0,r.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,r.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,r.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,r.yg)("h2",{id:"best-practices"},"Best practices"),(0,r.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] MyTranslator $translator): string"))),(0,r.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,r.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,r.yg)("pre",null,(0,r.yg)("code",null,"#[Field] public function getName(#[Autowire] TranslatorInterface $translator): string"))),(0,r.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,r.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,r.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Autowire(identifier: "translator")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')))),(0,r.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,r.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,r.yg)("ul",null,(0,r.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,r.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,r.yg)("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.yg)("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.7c7ff7e3.js b/assets/js/bb9fe7c3.7ddfdfab.js similarity index 99% rename from assets/js/bb9fe7c3.7c7ff7e3.js rename to assets/js/bb9fe7c3.7ddfdfab.js index 34b8b0920..b3b316076 100644 --- a/assets/js/bb9fe7c3.7c7ff7e3.js +++ b/assets/js/bb9fe7c3.7ddfdfab.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5832],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),i=a(20053);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.A)(o.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>N});var n=a(58168),i=a(96540),o=a(20053),r=a(23104),l=a(56347),s=a(57485),u=a(31682),d=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 m(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(!y({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]=h({queryString:a,groupId:n}),[p,m]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,d.Dv)(a);return[n,(0,i.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),g=(()=>{const e=s??p;return y({value:e,tabValues:o})?e:null})();(0,i.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!y({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),m(e)}),[u,m,o]),tabValues:o}}var g=a(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},y=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:r}=e;return i.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:y,onClick:c},r,{className:(0,o.A)("tabs__item",v.tabItem,r?.className,{"tabs__item--active":l===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,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 w(e){const t=m(e);return i.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},i.createElement(f,(0,n.A)({},e,t)),i.createElement(b,(0,n.A)({},e,t)))}function N(e){const t=(0,g.A)();return i.createElement(w,(0,n.A)({key:String(t)},e))}},71650:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var n=a(58168),i=(a(96540),a(15680));a(67443),a(11470),a(19365);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/6.1/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/validation.mdx",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"docs",previous:{title:"Error handling",permalink:"/docs/6.1/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/6.1/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.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,i.yg)("a",{parentName:"p",href:"/docs/6.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,i.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.yg)("pre",{parentName:"li"},(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,i.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,i.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.yg)("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.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.yg)("p",null,"You can also pass an array to the ",(0,i.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,i.yg)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"),(0,i.yg)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.yg)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.yg)("inlineCode",{parentName:"p"},"@Input")," annotation or PHP8 ",(0,i.yg)("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.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("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.yg)("p",null,"To get started with validation on input types defined by an ",(0,i.yg)("inlineCode",{parentName:"p"},"@Input")," annotation, you'll first need to register your validator with the ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Your input type validator must implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.yg)("p",null,"You'll notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.yg)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.yg)("p",null,"Also available is the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.yg)("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([[5832],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),i=a(20053);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.A)(o.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>N});var n=a(58168),i=a(96540),o=a(20053),r=a(23104),l=a(56347),s=a(57485),u=a(31682),d=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 m(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(!y({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]=h({queryString:a,groupId:n}),[p,m]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,o]=(0,d.Dv)(a);return[n,(0,i.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:n}),g=(()=>{const e=s??p;return y({value:e,tabValues:o})?e:null})();(0,i.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,i.useCallback)((e=>{if(!y({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),m(e)}),[u,m,o]),tabValues:o}}var g=a(92303);const v={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const d=[],{blockElementScrollPositionUntilNextRender:p}=(0,r.a_)(),c=e=>{const t=e.currentTarget,a=d.indexOf(t),n=u[a].value;n!==l&&(p(t),s(n))},y=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:r}=e;return i.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>d.push(e),onKeyDown:y,onClick:c},r,{className:(0,o.A)("tabs__item",v.tabItem,r?.className,{"tabs__item--active":l===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,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 w(e){const t=m(e);return i.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},i.createElement(f,(0,n.A)({},e,t)),i.createElement(b,(0,n.A)({},e,t)))}function N(e){const t=(0,g.A)();return i.createElement(w,(0,n.A)({key:String(t)},e))}},71650:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var n=a(58168),i=(a(96540),a(15680));a(67443),a(11470),a(19365);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/6.1/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/validation.mdx",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"validation",title:"Validation",sidebar_label:"User input validation"},sidebar:"docs",previous:{title:"Error handling",permalink:"/docs/6.1/error-handling"},next:{title:"Authentication and authorization",permalink:"/docs/6.1/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.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite does not handle user input validation by itself. It is out of its scope."),(0,i.yg)("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.yg)("h2",{id:"validating-user-input-with-laravel"},"Validating user input with Laravel"),(0,i.yg)("p",null,"If you are using Laravel, jump directly to the ",(0,i.yg)("a",{parentName:"p",href:"/docs/6.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,i.yg)("h2",{id:"validating-user-input-with-symfony-validator"},"Validating user input with Symfony validator"),(0,i.yg)("p",null,"GraphQLite provides a bridge to use the ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/validation.html"},"Symfony validator")," directly in your application."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("p",{parentName:"li"},"If you are using Symfony and the Symfony GraphQLite bundle, the bridge is available out of the box")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("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.yg)("em",{parentName:"p"},"thecodingmachine/graphqlite-symfony-validator-bridge")," package:"),(0,i.yg)("pre",{parentName:"li"},(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require thecodingmachine/graphqlite-symfony-validator-bridge\n")))),(0,i.yg)("h3",{id:"using-the-symfony-validator-bridge"},"Using the Symfony validator bridge"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"Validator")," object."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Validation rules are added directly to the object in the domain model:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'If a validation fails, GraphQLite will return the failed validations in the "errors" section of the JSON response:'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h3",{id:"using-the-validator-directly-on-a-query--mutation--factory-"},"Using the validator directly on a query / mutation / factory ..."),(0,i.yg)("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.yg)("p",null,"If the data entered by the user is ",(0,i.yg)("strong",{parentName:"p"},"not")," mapped to an object, you can directly annotate your query, mutation, factory..."),(0,i.yg)("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.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation to validate directly the user input."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'Notice that the "constraint" parameter contains an annotation (it is an annotation wrapped in an annotation).'),(0,i.yg)("p",null,"You can also pass an array to the ",(0,i.yg)("inlineCode",{parentName:"p"},"constraint")," parameter:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'@Assertion(for="email", constraint={@Assert\\NotBlank(), @Assert\\Email()})\n')),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!"),' The "@Assertion" annotation is only available as a ',(0,i.yg)("strong",null,"Doctrine annotations"),". You cannot use it as a PHP 8 attributes"),(0,i.yg)("h2",{id:"custom-inputtype-validation"},"Custom InputType Validation"),(0,i.yg)("p",null,"GraphQLite also supports a fully custom validation implementation for all input types defined with an ",(0,i.yg)("inlineCode",{parentName:"p"},"@Input")," annotation or PHP8 ",(0,i.yg)("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.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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.yg)("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.yg)("p",null,"To get started with validation on input types defined by an ",(0,i.yg)("inlineCode",{parentName:"p"},"@Input")," annotation, you'll first need to register your validator with the ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),"."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Your input type validator must implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Types\\InputTypeValidatorInterface"),", as shown below:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The interface is quite simple. Handle all of your own validation logic in the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"validate")," method will receive the input type object populated with the user input."),(0,i.yg)("p",null,"You'll notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"validate")," method has a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")," as usual (see ",(0,i.yg)("a",{parentName:"p",href:"error-handling"},"Error Handling")," for more details)."),(0,i.yg)("p",null,"Also available is the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"true")," to keep it always enabled."),(0,i.yg)("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.09da66bc.js b/assets/js/bcb6471f.da58a603.js similarity index 99% rename from assets/js/bcb6471f.09da66bc.js rename to assets/js/bcb6471f.da58a603.js index 2e5b3a1a7..9fa8060f5 100644 --- a/assets/js/bcb6471f.09da66bc.js +++ b/assets/js/bcb6471f.da58a603.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3196],{77375:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>o,default:()=>c,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=a(58168),r=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],y={toc:s},g="wrapper";function c(e){let{components:n,...a}=e;return(0,r.yg)(g,(0,t.A)({},y,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,r.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,r.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.yg)("p",null,"Now, go to the ",(0,r.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"config/packages/graphqlite.yaml")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,r.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,r.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,r.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"app/AppKernel.php")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>o,default:()=>c,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=a(58168),r=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],y={toc:s},g="wrapper";function c(e){let{components:n,...a}=e;return(0,r.yg)(g,(0,t.A)({},y,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"The GraphQLite bundle is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Symfony 4.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Symfony 5.x"),"."),(0,r.yg)("h2",{id:"applications-that-use-symfony-flex"},"Applications that use Symfony Flex"),(0,r.yg)("p",null,"Open a command console, enter your project directory and execute:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.yg)("p",null,"Now, go to the ",(0,r.yg)("inlineCode",{parentName:"p"},"config/packages/graphqlite.yaml")," file and edit the namespaces to match your application."),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"config/packages/graphqlite.yaml")),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"More advanced parameters are detailed in the ",(0,r.yg)("a",{parentName:"p",href:"#advanced-configuration"},'"advanced configuration" section')),(0,r.yg)("h2",{id:"applications-that-dont-use-symfony-flex"},"Applications that don't use Symfony Flex"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-bundle\n")),(0,r.yg)("p",null,"Enable the library by adding it to the list of registered bundles in the ",(0,r.yg)("inlineCode",{parentName:"p"},"app/AppKernel.php")," file:"),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"app/AppKernel.php")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/5.0/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2952],{30905:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/5.0/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/bd2c4a98.25345306.js b/assets/js/bd2c4a98.15bff0c5.js similarity index 99% rename from assets/js/bd2c4a98.25345306.js rename to assets/js/bd2c4a98.15bff0c5.js index aa5d4ebb6..ffa2d3c22 100644 --- a/assets/js/bd2c4a98.25345306.js +++ b/assets/js/bd2c4a98.15bff0c5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9026],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var r=a(96540),t=a(20053);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,t.A)(o.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>$});var r=a(58168),t=a(96540),o=a(20053),i=a(23104),l=a(56347),s=a(57485),c=a(31682),p=a(89466);function u(e){return function(e){return t.Children.map(e,(e=>{if(!e||(0,t.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:a,attributes:r,default:t}}=e;return{value:n,label:a,attributes:r,default:t}}))}function d(e){const{values:n,children:a}=e;return(0,t.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function h(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:a}=e;const r=(0,l.W6)(),o=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(o),(0,t.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 y(e){const{defaultValue:n,queryString:a=!1,groupId:r}=e,o=d(e),[i,l]=(0,t.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,c]=m({queryString:a,groupId:r}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,p.Dv)(a);return[r,(0,t.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:r}),g=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,t.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:i,selectValue:(0,t.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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),d=e=>{const n=e.currentTarget,a=p.indexOf(n),r=c[a].value;r!==l&&(u(n),s(r))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;n=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;n=p[a]??p[p.length-1];break}}n?.focus()};return t.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return t.createElement("li",(0,r.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":l===n})}),a??n)})))}function w(e){let{lazy:n,children:a,selectedValue:r}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,t.cloneElement)(e,{className:"margin-top--md"}):null}return t.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,t.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=y(e);return t.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},t.createElement(b,(0,r.A)({},e,n)),t.createElement(w,(0,r.A)({},e,n)))}function $(e){const n=(0,g.A)();return t.createElement(v,(0,r.A)({key:String(n)},e))}},30999:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var r=a(58168),t=(a(96540),a(15680)),o=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:n,...a}=e;return(0,t.yg)(h,(0,r.A)({},d,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,t.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("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([[9026],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var r=a(96540),t=a(20053);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,t.A)(o.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>$});var r=a(58168),t=a(96540),o=a(20053),i=a(23104),l=a(56347),s=a(57485),c=a(31682),p=a(89466);function u(e){return function(e){return t.Children.map(e,(e=>{if(!e||(0,t.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:a,attributes:r,default:t}}=e;return{value:n,label:a,attributes:r,default:t}}))}function d(e){const{values:n,children:a}=e;return(0,t.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function h(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:a}=e;const r=(0,l.W6)(),o=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(o),(0,t.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 y(e){const{defaultValue:n,queryString:a=!1,groupId:r}=e,o=d(e),[i,l]=(0,t.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,c]=m({queryString:a,groupId:r}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,p.Dv)(a);return[r,(0,t.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:r}),g=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,t.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:i,selectValue:(0,t.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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),d=e=>{const n=e.currentTarget,a=p.indexOf(n),r=c[a].value;r!==l&&(u(n),s(r))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;n=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;n=p[a]??p[p.length-1];break}}n?.focus()};return t.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return t.createElement("li",(0,r.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":l===n})}),a??n)})))}function w(e){let{lazy:n,children:a,selectedValue:r}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,t.cloneElement)(e,{className:"margin-top--md"}):null}return t.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,t.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=y(e);return t.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},t.createElement(b,(0,r.A)({},e,n)),t.createElement(w,(0,r.A)({},e,n)))}function $(e){const n=(0,g.A)();return t.createElement(v,(0,r.A)({key:String(n)},e))}},30999:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var r=a(58168),t=(a(96540),a(15680)),o=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:n,...a}=e;return(0,t.yg)(h,(0,r.A)({},d,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,t.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("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.f5b2adb7.js b/assets/js/bda39da3.a60d43a7.js similarity index 98% rename from assets/js/bda39da3.f5b2adb7.js rename to assets/js/bda39da3.a60d43a7.js index 1b17dd75f..43a3d2a6f 100644 --- a/assets/js/bda39da3.f5b2adb7.js +++ b/assets/js/bda39da3.a60d43a7.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6874],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>q});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),u=n(56347),s=n(57485),i=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&u(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}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":u===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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function q(e){const t=(0,y.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},1931:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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([[6874],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>q});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),u=n(56347),s=n(57485),i=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&u(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}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":u===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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function q(e){const t=(0,y.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},1931:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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.adf1fcbf.js b/assets/js/bdb33130.423bf6c8.js similarity index 99% rename from assets/js/bdb33130.adf1fcbf.js rename to assets/js/bdb33130.423bf6c8.js index 58dd66e0f..cab0a9d1b 100644 --- a/assets/js/bdb33130.adf1fcbf.js +++ b/assets/js/bdb33130.423bf6c8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5049],{94273:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>l,default:()=>m,frontMatter:()=>r,metadata:()=>s,toc:()=>c});var a=t(58168),i=(t(96540),t(15680));t(67443);const r={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},l=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},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},g="wrapper";function m(e){let{components:n,...t}=e;return(0,i.yg)(g,(0,a.A)({},o,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,i.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.yg)("p",null,"Written in ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.yg)("p",null,"The GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,i.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute on a PHP interface."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n")),(0,i.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,i.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.yg)("p",null,"This will translate in GraphQL schema as:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,i.yg)("p",null,"Please note that you do not need to put the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute again in the implementing class."),(0,i.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,i.yg)("p",null,"You don't have to explicitly put a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute on the class implementing the interface (though this\nis usually a good idea)."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute, GraphQLite will\ncreate a ",(0,i.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,i.yg)("pre",null,(0,i.yg)("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([[5049],{94273:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>l,default:()=>m,frontMatter:()=>r,metadata:()=>s,toc:()=>c});var a=t(58168),i=(t(96540),t(15680));t(67443);const r={id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"},l=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},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},g="wrapper";function m(e){let{components:n,...t}=e;return(0,i.yg)(g,(0,a.A)({},o,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,i.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n")),(0,i.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,i.yg)("p",null,"Written in ",(0,i.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,i.yg)("p",null,"The GraphQL ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,i.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,i.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,i.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,i.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute on a PHP interface."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n")),(0,i.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,i.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")),(0,i.yg)("p",null,"This will translate in GraphQL schema as:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,i.yg)("p",null,"Please note that you do not need to put the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute again in the implementing class."),(0,i.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,i.yg)("p",null,"You don't have to explicitly put a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute on the class implementing the interface (though this\nis usually a good idea)."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,i.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute, GraphQLite will\ncreate a ",(0,i.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,i.yg)("pre",null,(0,i.yg)("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/be1f0304.19cc57bd.js b/assets/js/be1f0304.ac099204.js similarity index 99% rename from assets/js/be1f0304.19cc57bd.js rename to assets/js/be1f0304.ac099204.js index c4eb2ca06..17de00287 100644 --- a/assets/js/be1f0304.19cc57bd.js +++ b/assets/js/be1f0304.ac099204.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6266],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var a=t(96540),r=t(20053);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.A)(l.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),r=t(96540),l=t(20053),i=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);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.X)(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 g(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,o.W6)(),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.aZ)(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 y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=d(e),[i,o]=(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(!g({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,p.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),m=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const n=e.currentTarget,t=p.indexOf(n),a=u[t].value;a!==o&&(c(n),s(a))},g=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,l.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(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 T(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(n)},e))}},424:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),i=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function h(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Using ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Let's break this sample:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.yg)("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.yg)("p",null,'Using the "',(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6266],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var a=t(96540),r=t(20053);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.A)(l.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),r=t(96540),l=t(20053),i=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);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.X)(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 g(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,o.W6)(),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.aZ)(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 y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=d(e),[i,o]=(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(!g({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,p.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),m=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const n=e.currentTarget,t=p.indexOf(n),a=u[t].value;a!==o&&(c(n),s(a))},g=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,l.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(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 T(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(n)},e))}},424:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),i=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function h(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Using ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Let's break this sample:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.yg)("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.yg)("p",null,'Using the "',(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/beccb025.2bce8e1f.js b/assets/js/beccb025.9437bedc.js similarity index 98% rename from assets/js/beccb025.2bce8e1f.js rename to assets/js/beccb025.9437bedc.js index f1c458963..ffcc0fd00 100644 --- a/assets/js/beccb025.2bce8e1f.js +++ b/assets/js/beccb025.9437bedc.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[247],{97386:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:p},u="wrapper";function d(e){let{components:t,...a}=e;return(0,i.yg)(u,(0,n.A)({},g,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,i.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,i.yg)("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.yg)("a",{href:"laravel-package-advanced"},"comes with its own pagination system"),"."),(0,i.yg)("h2",{id:"installation"},"Installation"),(0,i.yg)("p",null,"You will need to install the ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,i.yg)("h2",{id:"usage"},"Usage"),(0,i.yg)("p",null,"In your query, simply return a class that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Notice that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,i.yg)("li",{parentName:"ul"},"you MUST add a ",(0,i.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,i.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,i.yg)("p",null,'The "count" field returns the ',(0,i.yg)("strong",{parentName:"p"},"total count")," of items."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[247],{97386:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:p},u="wrapper";function d(e){let{components:t,...a}=e;return(0,i.yg)(u,(0,n.A)({},g,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,i.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,i.yg)("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.yg)("a",{href:"laravel-package-advanced"},"comes with its own pagination system"),"."),(0,i.yg)("h2",{id:"installation"},"Installation"),(0,i.yg)("p",null,"You will need to install the ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,i.yg)("h2",{id:"usage"},"Usage"),(0,i.yg)("p",null,"In your query, simply return a class that implements ",(0,i.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Notice that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,i.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,i.yg)("li",{parentName:"ul"},"you MUST add a ",(0,i.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,i.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,i.yg)("p",null,'The "count" field returns the ',(0,i.yg)("strong",{parentName:"p"},"total count")," of items."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/bf2a5963.0b8eb41a.js b/assets/js/bf2a5963.64c72590.js similarity index 99% rename from assets/js/bf2a5963.0b8eb41a.js rename to assets/js/bf2a5963.64c72590.js index 330f76516..5bce420e8 100644 --- a/assets/js/bf2a5963.0b8eb41a.js +++ b/assets/js/bf2a5963.64c72590.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8919],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),s=a(56347),i=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),h(e)}),[u,h,l]),tabValues:l}}var f=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},g=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},o,{className:(0,l.A)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":s===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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},45839:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(g,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"You will need to install the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"In your query, simply return a class that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.yg)("p",null,'The "count" field returns the ',(0,r.yg)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8919],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),s=a(56347),i=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),h(e)}),[u,h,l]),tabValues:l}}var f=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},g=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},o,{className:(0,l.A)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":s===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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},45839:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(g,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"You will need to install the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"In your query, simply return a class that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.yg)("p",null,'The "count" field returns the ',(0,r.yg)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/bfe5398f.45ffaac0.js b/assets/js/bfe5398f.26707152.js similarity index 97% rename from assets/js/bfe5398f.45ffaac0.js rename to assets/js/bfe5398f.26707152.js index 160eb5da9..e23cc4672 100644 --- a/assets/js/bfe5398f.45ffaac0.js +++ b/assets/js/bfe5398f.26707152.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2311],{90355:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-8.0.0/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-8.0.0/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/troubleshooting.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2311],{90355:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);const i={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},s=void 0,a={unversionedId:"troubleshooting",id:"version-8.0.0/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-8.0.0/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/troubleshooting.md",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c007fb39.c1bd0f68.js b/assets/js/c007fb39.4066ed8c.js similarity index 99% rename from assets/js/c007fb39.c1bd0f68.js rename to assets/js/c007fb39.4066ed8c.js index 1df190803..34d1772c7 100644 --- a/assets/js/c007fb39.c1bd0f68.js +++ b/assets/js/c007fb39.4066ed8c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[521],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>w});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),c=t(31682),u=t(89466);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,c.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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,c]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,u.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),c(e),y(e)}),[c,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),h=e=>{const n=e.currentTarget,t=u.indexOf(n),r=c[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=u.indexOf(e.currentTarget)+1;n=u[t]??u[0];break}case"ArrowLeft":{const t=u.indexOf(e.currentTarget)-1;n=u[t]??u[u.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.A)("tabs__item",f.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 v(e){const n=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function w(e){const n=(0,m.A)();return a.createElement(v,(0,r.A)({key:String(n)},e))}},69904:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>c,toc:()=>p});var r=t(58168),a=(t(96540),t(15680)),o=(t(67443),t(11470)),i=t(19365);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,c={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},u={},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 g(e){let{components:n,...t}=e;return(0,a.yg)(d,(0,r.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/6.0/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/6.0/laravel-package"},"Laravel"),")."),(0,a.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[521],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var r=t(96540),a=t(20053);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.A)(o.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>w});var r=t(58168),a=t(96540),o=t(20053),i=t(23104),l=t(56347),s=t(57485),c=t(31682),u=t(89466);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,c.X)(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 g(e){let{queryString:n=!1,groupId:t}=e;const r=(0,l.W6)(),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.aZ)(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 y(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,c]=g({queryString:t,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,u.Dv)(t);return[r,(0,a.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:r}),m=(()=>{const e=s??p;return d({value:e,tabValues:o})?e:null})();(0,a.useLayoutEffect)((()=>{m&&l(m)}),[m]);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),c(e),y(e)}),[c,y,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:s,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),h=e=>{const n=e.currentTarget,t=u.indexOf(n),r=c[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=u.indexOf(e.currentTarget)+1;n=u[t]??u[0];break}case"ArrowLeft":{const t=u.indexOf(e.currentTarget)-1;n=u[t]??u[u.length-1];break}}n?.focus()};return a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},n)},c.map((e=>{let{value:n,label:t,attributes:i}=e;return a.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>u.push(e),onKeyDown:d,onClick:h},i,{className:(0,o.A)("tabs__item",f.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 v(e){const n=y(e);return a.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},a.createElement(b,(0,r.A)({},e,n)),a.createElement(x,(0,r.A)({},e,n)))}function w(e){const n=(0,m.A)();return a.createElement(v,(0,r.A)({key:String(n)},e))}},69904:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>s,default:()=>g,frontMatter:()=>l,metadata:()=>c,toc:()=>p});var r=t(58168),a=(t(96540),t(15680)),o=(t(67443),t(11470)),i=t(19365);const l={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},s=void 0,c={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},u={},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 g(e){let{components:n,...t}=e;return(0,a.yg)(d,(0,r.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,a.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,a.yg)("p",null,"By default, when you throw a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,a.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,a.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,a.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,a.yg)("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.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,a.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,a.yg)("p",null,"will generate:"),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,a.yg)("p",null,"Rather that throwing the base ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,a.yg)("p",null,"Any exception that implements interface ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,a.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,a.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,a.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,a.yg)("pre",null,(0,a.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,a.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,a.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,a.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,a.yg)("p",null,"Actually, the ",(0,a.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,a.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,a.yg)("p",null,"If an exception that does not implement ",(0,a.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,a.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,a.yg)("p",null,"You can ",(0,a.yg)("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.yg)("a",{parentName:"p",href:"/docs/6.0/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/6.0/laravel-package"},"Laravel"),")."),(0,a.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c0fa6485.1913b948.js b/assets/js/c0fa6485.9174cb01.js similarity index 98% rename from assets/js/c0fa6485.1913b948.js rename to assets/js/c0fa6485.9174cb01.js index cb6349d50..a5405235a 100644 --- a/assets/js/c0fa6485.1913b948.js +++ b/assets/js/c0fa6485.9174cb01.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8414],{76890:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,a.A)({},u,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in GraphQLite 5.0"),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,i.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"Please note that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,i.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,i.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,i.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,i.yg)("div",{class:"alert alert--info"},(0,i.yg)("strong",null,"Heads up!"),"Some IDEs provide support for Doctrine annotations:",(0,i.yg)("ul",null,(0,i.yg)("li",null,"PhpStorm via the ",(0,i.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,i.yg)("li",null,"Eclipse via the ",(0,i.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,i.yg)("li",null,"Netbeans has native support")),(0,i.yg)("p",null,"We strongly recommend using an IDE that has Doctrine annotations support.")),(0,i.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.yg)("p",null,"The same code can be written this way:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.yg)("p",null,"They support the same attributes too."),(0,i.yg)("p",null,"A few notable differences:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,i.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,i.yg)("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.yg)("p",null,"Let's take an example with the ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.1/autowiring"},(0,i.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"PHP 7+")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"PHP 8")),(0,i.yg)("pre",null,(0,i.yg)("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([[8414],{76890:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,a.A)({},u,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in GraphQLite 5.0"),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,i.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"Please note that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,i.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,i.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,i.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,i.yg)("div",{class:"alert alert--info"},(0,i.yg)("strong",null,"Heads up!"),"Some IDEs provide support for Doctrine annotations:",(0,i.yg)("ul",null,(0,i.yg)("li",null,"PhpStorm via the ",(0,i.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,i.yg)("li",null,"Eclipse via the ",(0,i.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,i.yg)("li",null,"Netbeans has native support")),(0,i.yg)("p",null,"We strongly recommend using an IDE that has Doctrine annotations support.")),(0,i.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.yg)("p",null,"The same code can be written this way:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.yg)("p",null,"They support the same attributes too."),(0,i.yg)("p",null,"A few notable differences:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,i.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,i.yg)("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.yg)("p",null,"Let's take an example with the ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.1/autowiring"},(0,i.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"PHP 7+")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"PHP 8")),(0,i.yg)("pre",null,(0,i.yg)("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/c1068675.dbd64ae9.js b/assets/js/c1068675.ee46c7a9.js similarity index 98% rename from assets/js/c1068675.dbd64ae9.js rename to assets/js/c1068675.ee46c7a9.js index 1196d8b5f..5e55638b8 100644 --- a/assets/js/c1068675.dbd64ae9.js +++ b/assets/js/c1068675.ee46c7a9.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8607],{7936:(e,t,r)=>{r.r(t),r.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>h,frontMatter:()=>n,metadata:()=>u,toc:()=>d});var i=r(58168),s=(r(96540),r(15680)),a=r(67443);const n={id:"automatic-persisted-queries",title:"Automatic persisted queries",sidebar_label:"Automatic persisted queries"},o=void 0,u={unversionedId:"automatic-persisted-queries",id:"version-8.0.0/automatic-persisted-queries",title:"Automatic persisted queries",description:"The problem",source:"@site/versioned_docs/version-8.0.0/automatic-persisted-queries.mdx",sourceDirName:".",slug:"/automatic-persisted-queries",permalink:"/docs/automatic-persisted-queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/automatic-persisted-queries.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"automatic-persisted-queries",title:"Automatic persisted queries",sidebar_label:"Automatic persisted queries"},sidebar:"docs",previous:{title:"Prefetching records",permalink:"/docs/prefetch-method"},next:{title:"File uploads",permalink:"/docs/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.yg)(c,(0,i.A)({},p,r,{components:t,mdxType:"MDXLayout"}),(0,s.yg)("h2",{id:"the-problem"},"The problem"),(0,s.yg)("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.yg)("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.yg)("h2",{id:"apollo-apq"},"Apollo APQ"),(0,s.yg)("p",null,(0,s.yg)("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.yg)("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.yg)(a.K,{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.yg)("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.yg)("p",null,"Because query identifiers are deterministic hashes, clients can generate them at runtime. No additional build steps are required."),(0,s.yg)("h2",{id:"setup"},"Setup"),(0,s.yg)("p",null,"To use Automatic persisted queries with GraphQLite, you may use\n",(0,s.yg)("inlineCode",{parentName:"p"},"useAutomaticPersistedQueries")," method when building your PSR-15 middleware:"),(0,s.yg)("pre",null,(0,s.yg)("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([[8607],{7936:(e,t,r)=>{r.r(t),r.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>h,frontMatter:()=>n,metadata:()=>u,toc:()=>d});var i=r(58168),s=(r(96540),r(15680)),a=r(67443);const n={id:"automatic-persisted-queries",title:"Automatic persisted queries",sidebar_label:"Automatic persisted queries"},o=void 0,u={unversionedId:"automatic-persisted-queries",id:"version-8.0.0/automatic-persisted-queries",title:"Automatic persisted queries",description:"The problem",source:"@site/versioned_docs/version-8.0.0/automatic-persisted-queries.mdx",sourceDirName:".",slug:"/automatic-persisted-queries",permalink:"/docs/automatic-persisted-queries",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/automatic-persisted-queries.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"automatic-persisted-queries",title:"Automatic persisted queries",sidebar_label:"Automatic persisted queries"},sidebar:"docs",previous:{title:"Prefetching records",permalink:"/docs/prefetch-method"},next:{title:"File uploads",permalink:"/docs/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.yg)(c,(0,i.A)({},p,r,{components:t,mdxType:"MDXLayout"}),(0,s.yg)("h2",{id:"the-problem"},"The problem"),(0,s.yg)("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.yg)("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.yg)("h2",{id:"apollo-apq"},"Apollo APQ"),(0,s.yg)("p",null,(0,s.yg)("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.yg)("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.yg)(a.K,{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.yg)("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.yg)("p",null,"Because query identifiers are deterministic hashes, clients can generate them at runtime. No additional build steps are required."),(0,s.yg)("h2",{id:"setup"},"Setup"),(0,s.yg)("p",null,"To use Automatic persisted queries with GraphQLite, you may use\n",(0,s.yg)("inlineCode",{parentName:"p"},"useAutomaticPersistedQueries")," method when building your PSR-15 middleware:"),(0,s.yg)("pre",null,(0,s.yg)("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/c10d4a63.1fc0f2a8.js b/assets/js/c10d4a63.220b95fc.js similarity index 99% rename from assets/js/c10d4a63.1fc0f2a8.js rename to assets/js/c10d4a63.220b95fc.js index 35768c0bb..302078085 100644 --- a/assets/js/c10d4a63.1fc0f2a8.js +++ b/assets/js/c10d4a63.220b95fc.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1235],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),l=a(20053);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.A)(u.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>P});var n=a(58168),l=a(96540),u=a(20053),r=a(23104),i=a(56347),o=a(57485),p=a(31682),s=a(89466);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:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function d(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,p.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=d(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(!y({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]=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,u]=(0,s.Dv)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),g=(()=>{const e=o??c;return y({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),h(e)}),[p,h,u]),tabValues:u}}var g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),d=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(c(t),o(n))},y=e=>{let t=null;switch(e.key){case"Enter":d(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.A)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.A)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},r,{className:(0,u.A)("tabs__item",f.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 T(e){const t=h(e);return l.createElement("div",{className:(0,u.A)("tabs-container",f.tabList)},l.createElement(b,(0,n.A)({},e,t)),l.createElement(v,(0,n.A)({},e,t)))}function P(e){const t=(0,g.A)();return l.createElement(T,(0,n.A)({key:String(t)},e))}},71592:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>m,frontMatter:()=>i,metadata:()=>p,toc:()=>c});var n=a(58168),l=(a(96540),a(15680)),u=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},c=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:c},y="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/external-type-declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("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.yg)("p",null,"So instead of writing:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.yg)("p",null,"you will write:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1235],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),l=a(20053);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.A)(u.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>P});var n=a(58168),l=a(96540),u=a(20053),r=a(23104),i=a(56347),o=a(57485),p=a(31682),s=a(89466);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:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function d(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,p.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=d(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(!y({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]=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,u]=(0,s.Dv)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),g=(()=>{const e=o??c;return y({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),h(e)}),[p,h,u]),tabValues:u}}var g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),d=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(c(t),o(n))},y=e=>{let t=null;switch(e.key){case"Enter":d(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.A)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.A)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},r,{className:(0,u.A)("tabs__item",f.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 T(e){const t=h(e);return l.createElement("div",{className:(0,u.A)("tabs-container",f.tabList)},l.createElement(b,(0,n.A)({},e,t)),l.createElement(v,(0,n.A)({},e,t)))}function P(e){const t=(0,g.A)();return l.createElement(T,(0,n.A)({key:String(t)},e))}},71592:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>m,frontMatter:()=>i,metadata:()=>p,toc:()=>c});var n=a(58168),l=(a(96540),a(15680)),u=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},c=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:c},y="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/6.0/external-type-declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("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.yg)("p",null,"So instead of writing:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.yg)("p",null,"you will write:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c1fe0282.9222037b.js b/assets/js/c1fe0282.80c470cf.js similarity index 99% rename from assets/js/c1fe0282.9222037b.js rename to assets/js/c1fe0282.80c470cf.js index eb68524d5..5d18ae326 100644 --- a/assets/js/c1fe0282.9222037b.js +++ b/assets/js/c1fe0282.80c470cf.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6912],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var r=a(96540),t=a(20053);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,t.A)(o.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>$});var r=a(58168),t=a(96540),o=a(20053),i=a(23104),l=a(56347),s=a(57485),c=a(31682),p=a(89466);function u(e){return function(e){return t.Children.map(e,(e=>{if(!e||(0,t.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:a,attributes:r,default:t}}=e;return{value:n,label:a,attributes:r,default:t}}))}function d(e){const{values:n,children:a}=e;return(0,t.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function h(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:a}=e;const r=(0,l.W6)(),o=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(o),(0,t.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 y(e){const{defaultValue:n,queryString:a=!1,groupId:r}=e,o=d(e),[i,l]=(0,t.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,c]=m({queryString:a,groupId:r}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,p.Dv)(a);return[r,(0,t.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:r}),g=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,t.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:i,selectValue:(0,t.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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),d=e=>{const n=e.currentTarget,a=p.indexOf(n),r=c[a].value;r!==l&&(u(n),s(r))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;n=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;n=p[a]??p[p.length-1];break}}n?.focus()};return t.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return t.createElement("li",(0,r.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":l===n})}),a??n)})))}function w(e){let{lazy:n,children:a,selectedValue:r}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,t.cloneElement)(e,{className:"margin-top--md"}):null}return t.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,t.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=y(e);return t.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},t.createElement(b,(0,r.A)({},e,n)),t.createElement(w,(0,r.A)({},e,n)))}function $(e){const n=(0,g.A)();return t.createElement(v,(0,r.A)({key:String(n)},e))}},70157:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var r=a(58168),t=(a(96540),a(15680)),o=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:n,...a}=e;return(0,t.yg)(h,(0,r.A)({},d,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,t.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("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([[6912],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var r=a(96540),t=a(20053);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,t.A)(o.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>$});var r=a(58168),t=a(96540),o=a(20053),i=a(23104),l=a(56347),s=a(57485),c=a(31682),p=a(89466);function u(e){return function(e){return t.Children.map(e,(e=>{if(!e||(0,t.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:a,attributes:r,default:t}}=e;return{value:n,label:a,attributes:r,default:t}}))}function d(e){const{values:n,children:a}=e;return(0,t.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function h(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:a}=e;const r=(0,l.W6)(),o=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(o),(0,t.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 y(e){const{defaultValue:n,queryString:a=!1,groupId:r}=e,o=d(e),[i,l]=(0,t.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,c]=m({queryString:a,groupId:r}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,p.Dv)(a);return[r,(0,t.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:r}),g=(()=>{const e=s??u;return h({value:e,tabValues:o})?e:null})();(0,t.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:i,selectValue:(0,t.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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:s,tabValues:c}=e;const p=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),d=e=>{const n=e.currentTarget,a=p.indexOf(n),r=c[a].value;r!==l&&(u(n),s(r))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=p.indexOf(e.currentTarget)+1;n=p[a]??p[0];break}case"ArrowLeft":{const a=p.indexOf(e.currentTarget)-1;n=p[a]??p[p.length-1];break}}n?.focus()};return t.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return t.createElement("li",(0,r.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":l===n})}),a??n)})))}function w(e){let{lazy:n,children:a,selectedValue:r}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,t.cloneElement)(e,{className:"margin-top--md"}):null}return t.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,t.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=y(e);return t.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},t.createElement(b,(0,r.A)({},e,n)),t.createElement(w,(0,r.A)({},e,n)))}function $(e){const n=(0,g.A)();return t.createElement(v,(0,r.A)({key:String(n)},e))}},70157:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>c,toc:()=>u});var r=a(58168),t=(a(96540),a(15680)),o=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:n,...a}=e;return(0,t.yg)(h,(0,r.A)({},d,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,t.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("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.69c19950.js b/assets/js/c275698c.e823393f.js similarity index 99% rename from assets/js/c275698c.69c19950.js rename to assets/js/c275698c.e823393f.js index 775b8ab48..3b5a50ad6 100644 --- a/assets/js/c275698c.69c19950.js +++ b/assets/js/c275698c.e823393f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2248],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var a=t(96540),r=t(20053);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.A)(l.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),r=t(96540),l=t(20053),i=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);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.X)(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 g(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,o.W6)(),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.aZ)(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 y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=d(e),[i,o]=(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(!g({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,p.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),m=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const n=e.currentTarget,t=p.indexOf(n),a=u[t].value;a!==o&&(c(n),s(a))},g=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,l.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(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 T(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(n)},e))}},4743:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),i=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function h(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Using ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Let's break this sample:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.yg)("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.yg)("p",null,'Using the "',(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2248],{19365:(e,n,t)=>{t.d(n,{A:()=>i});var a=t(96540),r=t(20053);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.A)(l.tabItem,i),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),r=t(96540),l=t(20053),i=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);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.X)(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 g(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,o.W6)(),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.aZ)(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 y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,l=d(e),[i,o]=(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(!g({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,p.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:a}),m=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&o(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({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 m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const n=e.currentTarget,t=p.indexOf(n),a=u[t].value;a!==o&&(c(n),s(a))},g=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,l.A)("tabs",{"tabs--block":t},n)},u.map((e=>{let{value:n,label:t,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(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 T(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,m.A)();return r.createElement(T,(0,a.A)({key:String(n)},e))}},4743:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var a=t(58168),r=(t(96540),t(15680)),l=(t(67443),t(11470)),i=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function h(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,r.yg)("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.yg)("a",{href:"inheritance-interfaces"},"Inheritance")," section"),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,r.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,r.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Using ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,r.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Let's break this sample:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,r.yg)("p",null,"With the ",(0,r.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,r.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,r.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,r.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,r.yg)("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.yg)("p",null,'Using the "',(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,r.yg)("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."))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c329487f.50e7520e.js b/assets/js/c329487f.4fe1c35b.js similarity index 99% rename from assets/js/c329487f.50e7520e.js rename to assets/js/c329487f.4fe1c35b.js index d64042303..8e2291d71 100644 --- a/assets/js/c329487f.50e7520e.js +++ b/assets/js/c329487f.4fe1c35b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9249],{29974:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>r,metadata:()=>l,toc:()=>p});var t=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function u(e){let{components:a,...n}=e;return(0,i.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"40"},"4.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("p",null,"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/error-handling"},"GraphQL errors")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")),(0,i.yg)("li",{parentName:"ul"},'You can specify the HTTP response code to send with a given error, and the errors "extensions" section'),(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can map ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory")," annotations)"),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/extend_input_type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("p",null,"Symfony:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("p",null,"Laravel:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("p",null,"Internals:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9249],{29974:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>r,metadata:()=>l,toc:()=>p});var t=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function u(e){let{components:a,...n}=e;return(0,i.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"40"},"4.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("p",null,"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/error-handling"},"GraphQL errors")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")),(0,i.yg)("li",{parentName:"ul"},'You can specify the HTTP response code to send with a given error, and the errors "extensions" section'),(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can map ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory")," annotations)"),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/extend_input_type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("p",null,"Symfony:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("p",null,"Laravel:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("p",null,"Internals:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c32ff706.5698427e.js b/assets/js/c32ff706.4951bde3.js similarity index 96% rename from assets/js/c32ff706.5698427e.js rename to assets/js/c32ff706.4951bde3.js index 1a09c46ee..1167ec9ad 100644 --- a/assets/js/c32ff706.5698427e.js +++ b/assets/js/c32ff706.4951bde3.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9594],{38842:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>p,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(58168),i=(n(96540),n(15680));n(67443);const o={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,r={unversionedId:"mutations",id:"version-8.0.0/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-8.0.0/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/mutations.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/queries"},next:{title:"Subscriptions",permalink:"/docs/subscriptions"}},u={},d=[],l={toc:d},c="wrapper";function p(t){let{components:e,...n}=t;return(0,i.yg)(c,(0,a.A)({},l,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, mutations are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/queries"},"like queries"),"."),(0,i.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," attribute."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("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")))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9594],{38842:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>s,default:()=>p,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var a=n(58168),i=(n(96540),n(15680));n(67443);const o={id:"mutations",title:"Mutations",sidebar_label:"Mutations"},s=void 0,r={unversionedId:"mutations",id:"version-8.0.0/mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/versioned_docs/version-8.0.0/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-8.0.0/mutations.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/queries"},next:{title:"Subscriptions",permalink:"/docs/subscriptions"}},u={},d=[],l={toc:d},c="wrapper";function p(t){let{components:e,...n}=t;return(0,i.yg)(c,(0,a.A)({},l,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In GraphQLite, mutations are created ",(0,i.yg)("a",{parentName:"p",href:"/docs/queries"},"like queries"),"."),(0,i.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Mutation]")," attribute."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("pre",null,(0,i.yg)("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")))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c3701568.dbcc1dc8.js b/assets/js/c3701568.cab1ce33.js similarity index 98% rename from assets/js/c3701568.dbcc1dc8.js rename to assets/js/c3701568.cab1ce33.js index 3f4ab48bc..f51002851 100644 --- a/assets/js/c3701568.dbcc1dc8.js +++ b/assets/js/c3701568.cab1ce33.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1968],{32369:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>p,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=i(58168),a=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},c=[{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}],u={toc:c},d="wrapper";function p(e){let{components:t,...i}=e;return(0,a.yg)(d,(0,n.A)({},u,i,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,a.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,a.yg)("p",null,"Most of the time, your ",(0,a.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,a.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,a.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,a.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,a.yg)("h2",{id:"best-practices"},"Best practices"),(0,a.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,a.yg)("pre",null,(0,a.yg)("code",null," /** * @Field() */ public function getName(MyTranslator $translator): string"))),(0,a.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,a.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,a.yg)("pre",null,(0,a.yg)("code",null," /** * @Field() */ public function getName(TranslatorInterface $translator): string"))),(0,a.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,a.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,a.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')),(0,a.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,a.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,a.yg)("ul",null,(0,a.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,a.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,a.yg)("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.yg)("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([[1968],{32369:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>p,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var n=i(58168),a=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},c=[{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}],u={toc:c},d="wrapper";function p(e){let{components:t,...i}=e;return(0,a.yg)(d,(0,n.A)({},u,i,{components:t,mdxType:"MDXLayout"}),(0,a.yg)("p",null,"GraphQLite can automatically inject services in your fields/queries/mutations signatures."),(0,a.yg)("p",null,"Some of your fields may be computed. In order to compute these fields, you might need to call a service."),(0,a.yg)("p",null,"Most of the time, your ",(0,a.yg)("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.yg)("h2",{id:"sample"},"Sample"),(0,a.yg)("p",null,"Let's assume you are running an international store. You have a ",(0,a.yg)("inlineCode",{parentName:"p"},"Product")," class. Each product has many names (depending\non the language of the user)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"When GraphQLite queries the name, it will automatically fetch the translator service."),(0,a.yg)("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.yg)("code",null,"Symfony\\Component\\Translation\\TranslatorInterface"),"."),(0,a.yg)("h2",{id:"best-practices"},"Best practices"),(0,a.yg)("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.yg)("div",{class:"alert alert--danger"},"Please don't do that:",(0,a.yg)("pre",null,(0,a.yg)("code",null," /** * @Field() */ public function getName(MyTranslator $translator): string"))),(0,a.yg)("p",null,"Instead, be sure to type-hint against an interface."),(0,a.yg)("div",{class:"alert alert--success"},"Do this instead:",(0,a.yg)("pre",null,(0,a.yg)("code",null," /** * @Field() */ public function getName(TranslatorInterface $translator): string"))),(0,a.yg)("p",null,"By type-hinting against an interface, your code remains testable and is decoupled from the service implementation."),(0,a.yg)("h2",{id:"fetching-a-service-by-name-discouraged"},"Fetching a service by name (discouraged!)"),(0,a.yg)("p",null,"Optionally, you can specify the identifier of the service you want to fetch from the controller:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Autowire(for="$translator", identifier="translator")\n */\n')),(0,a.yg)("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.yg)("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.yg)("h2",{id:"alternative-solution"},"Alternative solution"),(0,a.yg)("p",null,"You may find yourself uncomfortable with the autowiring mechanism of GraphQLite. For instance maybe:"),(0,a.yg)("ul",null,(0,a.yg)("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.yg)("li",{parentName:"ul"},"You do not want to inject a service in a domain object"),(0,a.yg)("li",{parentName:"ul"},"You simply do not like the magic of injecting services in a method signature")),(0,a.yg)("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.yg)("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.db54eec4.js b/assets/js/c4d37b36.ec117dcc.js similarity index 99% rename from assets/js/c4d37b36.db54eec4.js rename to assets/js/c4d37b36.ec117dcc.js index 52f9a5693..0d7ba2751 100644 --- a/assets/js/c4d37b36.db54eec4.js +++ b/assets/js/c4d37b36.ec117dcc.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1141],{71680:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var t=n(58168),r=(n(96540),n(15680));n(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom annotations",permalink:"/docs/6.1/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/6.1/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},g="wrapper";function d(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},m,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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([[1141],{71680:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var t=n(58168),r=(n(96540),n(15680));n(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom annotations",permalink:"/docs/6.1/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/6.1/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},g="wrapper";function d(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},m,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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/c5fa393d.6e77de51.js b/assets/js/c5fa393d.e1f9c3bd.js similarity index 98% rename from assets/js/c5fa393d.6e77de51.js rename to assets/js/c5fa393d.e1f9c3bd.js index e7f579c93..bf6ca4439 100644 --- a/assets/js/c5fa393d.6e77de51.js +++ b/assets/js/c5fa393d.e1f9c3bd.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2605],{97524:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>r,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>l});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,i.yg)(h,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,i.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,i.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,i.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,i.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/fine-grained-security"},(0,i.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,i.yg)("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.yg)("br",null),"See ",(0,i.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,i.yg)("h2",{id:"logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,i.yg)("p",null,"GraphQLite exposes two annotations (",(0,i.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, the query ",(0,i.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,i.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,i.yg)("p",null,(0,i.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,i.yg)("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.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,i.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.0/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,i.yg)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2605],{97524:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>r,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>l});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,i.yg)(h,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,i.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,i.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,i.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,i.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.0/fine-grained-security"},(0,i.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,i.yg)("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.yg)("br",null),"See ",(0,i.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,i.yg)("h2",{id:"logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,i.yg)("p",null,"GraphQLite exposes two annotations (",(0,i.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, the query ",(0,i.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,i.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,i.yg)("p",null,(0,i.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,i.yg)("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.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,i.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.0/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,i.yg)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c69dda99.f81fee58.js b/assets/js/c69dda99.c65ae7cf.js similarity index 99% rename from assets/js/c69dda99.f81fee58.js rename to assets/js/c69dda99.c65ae7cf.js index 95c85d42c..2cefd4ffe 100644 --- a/assets/js/c69dda99.f81fee58.js +++ b/assets/js/c69dda99.c65ae7cf.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6192],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(l.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),l=a(20053),u=a(23104),o=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.W6)(),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.aZ)(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 h(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]=g({queryString:a,groupId:n}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);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),h(e)}),[i,h,l]),tabValues:l}}var b=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.tabItem,u?.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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(f,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function T(e){const t=(0,b.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},2730:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},p=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6192],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(l.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>T});var n=a(58168),r=a(96540),l=a(20053),u=a(23104),o=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{queryString:t=!1,groupId:a}=e;const n=(0,o.W6)(),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.aZ)(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 h(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]=g({queryString:a,groupId:n}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),b=(()=>{const e=s??p;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{b&&o(b)}),[b]);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),h(e)}),[i,h,l]),tabValues:l}}var b=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:a,selectedValue:o,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.tabItem,u?.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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(f,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function T(e){const t=(0,b.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},2730:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>g,frontMatter:()=>o,metadata:()=>i,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},p=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],d={toc:p},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",{align:"center"},(0,r.yg)("img",{src:"https://graphqlite.thecodingmachine.io/img/logo.svg",alt:"GraphQLite logo",width:"250",height:"250"})),(0,r.yg)("p",null,"A PHP library that allows you to write your GraphQL queries in simple-to-write controllers."),(0,r.yg)("h2",{id:"features"},"Features"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Create a complete GraphQL API by simply annotating your PHP classes"),(0,r.yg)("li",{parentName:"ul"},"Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!"),(0,r.yg)("li",{parentName:"ul"},"Comes with batteries included: queries, mutations, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!")),(0,r.yg)("h2",{id:"basic-example"},"Basic example"),(0,r.yg)("p",null,"First, declare a query in your controller:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, annotate the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class to declare what fields are exposed to the GraphQL API:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"That's it, you're good to go! Query and enjoy!"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n product(id: 42) {\n name\n }\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c6df2ddc.421fe189.js b/assets/js/c6df2ddc.78d6c143.js similarity index 99% rename from assets/js/c6df2ddc.421fe189.js rename to assets/js/c6df2ddc.78d6c143.js index 0e558189c..51d1b82bc 100644 --- a/assets/js/c6df2ddc.421fe189.js +++ b/assets/js/c6df2ddc.78d6c143.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7371],{75882:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>p,frontMatter:()=>r,metadata:()=>s,toc:()=>l});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},o=void 0,s={unversionedId:"fine-grained-security",id:"version-8.0.0/fine-grained-security",title:"Fine grained security",description:"If the #[Logged] and #[Right] attributes are not",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/fine-grained-security.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},u={},l=[{value:"Using the #Security attribute",id:"using-the-security-attribute",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:l},g="wrapper";function p(e){let{components:t,...n}=e;return(0,i.yg)(g,(0,a.A)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"If the ",(0,i.yg)("a",{parentName:"p",href:"/docs/authentication-authorization#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"#[Logged]")," and ",(0,i.yg)("inlineCode",{parentName:"a"},"#[Right]")," attributes")," are not\ngranular enough for your needs, you can use the advanced ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute."),(0,i.yg)("p",null,"Using the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute, you can write an ",(0,i.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,i.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,i.yg)("li",{parentName:"ul"},"...")),(0,i.yg)("h2",{id:"using-the-security-attribute"},"Using the #","[Security]"," attribute"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute must conform to ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,i.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,i.yg)("code",null,"#[Security]")," attribute. Most of the inspiration of this attribute comes from Symfony. Warning though! GraphQLite's ",(0,i.yg)("code",null,"#[Security]")," attribute and Symfony's ",(0,i.yg)("code",null,"#[Security]")," attribute are slightly different. Especially, the two attributes do not live in the same namespace!"),(0,i.yg)("h2",{id:"the-is_granted-function"},"The ",(0,i.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n")),(0,i.yg)("p",null,"is similar to"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n')),(0,i.yg)("p",null,"In addition, the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, the ",(0,i.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,i.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,i.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," expression."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security attribute purpose to do simple input validation."),(0,i.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,i.yg)("a",{parentName:"p",href:"/docs/authentication-authorization#not-throwing-errors"},(0,i.yg)("inlineCode",{parentName:"a"},"#[FailWith]")," attribute"),"\nbut for a given ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute."),(0,i.yg)("p",null,"You cannot use the ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,i.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n')),(0,i.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute can be used in any query, mutation or field, so anywhere you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Mutation]"),"\nor ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute."),(0,i.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n")),(0,i.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,i.yg)("p",null,"If you are using Laravel, you will ",(0,i.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,i.yg)("p",null,"If you are using another framework, you need to know that the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,i.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,i.yg)("a",{parentName:"p",href:"/docs/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7371],{75882:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>p,frontMatter:()=>r,metadata:()=>s,toc:()=>l});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security"},o=void 0,s={unversionedId:"fine-grained-security",id:"version-8.0.0/fine-grained-security",title:"Fine grained security",description:"If the #[Logged] and #[Right] attributes are not",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/fine-grained-security.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},u={},l=[{value:"Using the #Security attribute",id:"using-the-security-attribute",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:l},g="wrapper";function p(e){let{components:t,...n}=e;return(0,i.yg)(g,(0,a.A)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"If the ",(0,i.yg)("a",{parentName:"p",href:"/docs/authentication-authorization#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"#[Logged]")," and ",(0,i.yg)("inlineCode",{parentName:"a"},"#[Right]")," attributes")," are not\ngranular enough for your needs, you can use the advanced ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute."),(0,i.yg)("p",null,"Using the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute, you can write an ",(0,i.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,i.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,i.yg)("li",{parentName:"ul"},"...")),(0,i.yg)("h2",{id:"using-the-security-attribute"},"Using the #","[Security]"," attribute"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute must conform to ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,i.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,i.yg)("code",null,"#[Security]")," attribute. Most of the inspiration of this attribute comes from Symfony. Warning though! GraphQLite's ",(0,i.yg)("code",null,"#[Security]")," attribute and Symfony's ",(0,i.yg)("code",null,"#[Security]")," attribute are slightly different. Especially, the two attributes do not live in the same namespace!"),(0,i.yg)("h2",{id:"the-is_granted-function"},"The ",(0,i.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n")),(0,i.yg)("p",null,"is similar to"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n')),(0,i.yg)("p",null,"In addition, the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, the ",(0,i.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,i.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,i.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," expression."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security attribute purpose to do simple input validation."),(0,i.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,i.yg)("a",{parentName:"p",href:"/docs/authentication-authorization#not-throwing-errors"},(0,i.yg)("inlineCode",{parentName:"a"},"#[FailWith]")," attribute"),"\nbut for a given ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute."),(0,i.yg)("p",null,"You cannot use the ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,i.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n')),(0,i.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Security]")," attribute can be used in any query, mutation or field, so anywhere you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Query]"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Mutation]"),"\nor ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute."),(0,i.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n")),(0,i.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,i.yg)("p",null,"If you are using Laravel, you will ",(0,i.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,i.yg)("p",null,"If you are using another framework, you need to know that the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,i.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,i.yg)("a",{parentName:"p",href:"/docs/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c7a4caa1.e682f287.js b/assets/js/c7a4caa1.8813fc32.js similarity index 98% rename from assets/js/c7a4caa1.e682f287.js rename to assets/js/c7a4caa1.8813fc32.js index adac78871..28b101970 100644 --- a/assets/js/c7a4caa1.e682f287.js +++ b/assets/js/c7a4caa1.8813fc32.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1308],{2393:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>v,frontMatter:()=>t,metadata:()=>s,toc:()=>l});var n=i(58168),a=(i(96540),i(15680));i(67443);const t={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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,a.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,a.yg)("p",null,(0,a.yg)("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,a.yg)("p",null,"If your framework is compatible with ",(0,a.yg)("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,a.yg)("h2",{id:"installation"},"Installation"),(0,a.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,a.yg)("h2",{id:"requirements"},"Requirements"),(0,a.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,a.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,a.yg)("p",null,"GraphQLite relies on the ",(0,a.yg)("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,a.yg)("a",{parentName:"p",href:"https://github.com/phps-cans/psr7-middleware-graphql"},"PSR-15 middleware available"),"."),(0,a.yg)("h2",{id:"integration"},"Integration"),(0,a.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,a.yg)("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,a.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,a.yg)("p",null,(0,a.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,a.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,a.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"composer.json")),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"index.php")),(0,a.yg)("pre",null,(0,a.yg)("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([[1308],{2393:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>v,frontMatter:()=>t,metadata:()=>s,toc:()=>l});var n=i(58168),a=(i(96540),i(15680));i(67443);const t={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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,a.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,a.yg)("p",null,(0,a.yg)("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,a.yg)("p",null,"If your framework is compatible with ",(0,a.yg)("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,a.yg)("h2",{id:"installation"},"Installation"),(0,a.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,a.yg)("pre",null,(0,a.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,a.yg)("h2",{id:"requirements"},"Requirements"),(0,a.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,a.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,a.yg)("p",null,"GraphQLite relies on the ",(0,a.yg)("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,a.yg)("a",{parentName:"p",href:"https://github.com/phps-cans/psr7-middleware-graphql"},"PSR-15 middleware available"),"."),(0,a.yg)("h2",{id:"integration"},"Integration"),(0,a.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,a.yg)("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,a.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,a.yg)("p",null,(0,a.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,a.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,a.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"composer.json")),(0,a.yg)("pre",null,(0,a.yg)("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,a.yg)("p",null,(0,a.yg)("strong",{parentName:"p"},"index.php")),(0,a.yg)("pre",null,(0,a.yg)("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.90632fce.js b/assets/js/c7e7ae18.ee32871a.js similarity index 99% rename from assets/js/c7e7ae18.90632fce.js rename to assets/js/c7e7ae18.ee32871a.js index 46a541556..696cce96b 100644 --- a/assets/js/c7e7ae18.90632fce.js +++ b/assets/js/c7e7ae18.ee32871a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[152],{79070:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>y,frontMatter:()=>r,metadata:()=>l,toc:()=>u});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"input-types",title:"Input types",sidebar_label:"Input types"},o=void 0,l={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},p={},u=[{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}],s={toc:u},d="wrapper";function y(e){let{components:t,...n}=e;return(0,i.yg)(d,(0,a.A)({},s,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,i.yg)("p",null,"Your GraphQL query might look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,i.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,i.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,i.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,i.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,i.yg)("a",{parentName:"p",href:"#input-attribute"},(0,i.yg)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,i.yg)("a",{parentName:"p",href:"#factory"},"Factory method"),"."),(0,i.yg)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,i.yg)("p",null,"Using the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Now if you call the ",(0,i.yg)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,i.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,i.yg)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,i.yg)("p",null,"There are some important things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," attribute is recognized on properties for Input Type, as well as setters."),(0,i.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,i.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,i.yg)("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,i.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," attribute on the setter, instead of the property, allowing you to have use many other attributes (",(0,i.yg)("inlineCode",{parentName:"li"},"Security"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,i.yg)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,i.yg)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,i.yg)("li",{parentName:"ul"},"It's advised to use the ",(0,i.yg)("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,i.yg)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,i.yg)("p",null,"Simple usage of the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]"),' attribute 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,i.yg)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," class."),(0,i.yg)("p",null,"You can add multiple ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]")," attributed to the same class, give them different names and link different fields.\nConsider the following example:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"There are 2 input types added to the ",(0,i.yg)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,i.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,i.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,i.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,i.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,i.yg)("p",null,"Note that ",(0,i.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,i.yg)("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,i.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,i.yg)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,i.yg)("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,i.yg)("h2",{id:"factory"},"Factory"),(0,i.yg)("p",null,"A ",(0,i.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,i.yg)("p",null,"Here is an example of factory:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory attribute 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,i.yg)("p",null,"and now, you can run query like this:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,i.yg)("strong",{parentName:"li"},"#","[Factory]")," attribute."),(0,i.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,i.yg)("p",null,"A few important things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,i.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,i.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,i.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the #',"[Factory]"," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n")),(0,i.yg)("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,i.yg)("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,i.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[UseInputType]")," attribute to force an input type of a parameter."),(0,i.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,i.yg)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,i.yg)("inlineCode",{parentName:"p"},"#[UseInputType]")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Factory]")," attribute to achieve your goal."),(0,i.yg)("p",null,"Here is an annotated sample:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("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,i.yg)("p",null,"Image your ",(0,i.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,i.yg)("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,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"With the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[HideParameter]")," attribute, you can choose to remove from the GraphQL schema any argument."),(0,i.yg)("p",null,"To be able to hide an argument, the argument must have a default value."))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[152],{79070:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>o,default:()=>y,frontMatter:()=>r,metadata:()=>l,toc:()=>u});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"input-types",title:"Input types",sidebar_label:"Input types"},o=void 0,l={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},p={},u=[{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}],s={toc:u},d="wrapper";function y(e){let{components:t,...n}=e;return(0,i.yg)(d,(0,a.A)({},s,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,i.yg)("p",null,"Your GraphQL query might look like this:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,i.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,i.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,i.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,i.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,i.yg)("a",{parentName:"p",href:"#input-attribute"},(0,i.yg)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,i.yg)("a",{parentName:"p",href:"#factory"},"Factory method"),"."),(0,i.yg)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,i.yg)("p",null,"Using the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Now if you call the ",(0,i.yg)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,i.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,i.yg)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,i.yg)("p",null,"There are some important things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," attribute is recognized on properties for Input Type, as well as setters."),(0,i.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,i.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,i.yg)("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,i.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," attribute on the setter, instead of the property, allowing you to have use many other attributes (",(0,i.yg)("inlineCode",{parentName:"li"},"Security"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,i.yg)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,i.yg)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,i.yg)("li",{parentName:"ul"},"It's advised to use the ",(0,i.yg)("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,i.yg)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,i.yg)("p",null,"Simple usage of the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]"),' attribute 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,i.yg)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,i.yg)("inlineCode",{parentName:"p"},"Location")," class."),(0,i.yg)("p",null,"You can add multiple ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Input]")," attributed to the same class, give them different names and link different fields.\nConsider the following example:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"There are 2 input types added to the ",(0,i.yg)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,i.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,i.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,i.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,i.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,i.yg)("li",{parentName:"ul"},"Field ",(0,i.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,i.yg)("p",null,"Note that ",(0,i.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,i.yg)("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,i.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,i.yg)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,i.yg)("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,i.yg)("h2",{id:"factory"},"Factory"),(0,i.yg)("p",null,"A ",(0,i.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,i.yg)("p",null,"Here is an example of factory:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"class MyFactory\n{\n /**\n * The Factory attribute 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,i.yg)("p",null,"and now, you can run query like this:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,i.yg)("strong",{parentName:"li"},"#","[Factory]")," attribute."),(0,i.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,i.yg)("p",null,"A few important things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,i.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,i.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,i.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the #',"[Factory]"," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n")),(0,i.yg)("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,i.yg)("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,i.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[UseInputType]")," attribute to force an input type of a parameter."),(0,i.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,i.yg)("p",null,"This is often the case when your objects map database entities.\nIn these cases, you can use combine the use of ",(0,i.yg)("inlineCode",{parentName:"p"},"#[UseInputType]")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Factory]")," attribute to achieve your goal."),(0,i.yg)("p",null,"Here is an annotated sample:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("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,i.yg)("p",null,"Image your ",(0,i.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,i.yg)("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,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"With the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[HideParameter]")," attribute, you can choose to remove from the GraphQL schema any argument."),(0,i.yg)("p",null,"To be able to hide an argument, the argument must have a default value."))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c8bdc4df.d594a844.js b/assets/js/c8bdc4df.3e4aebed.js similarity index 98% rename from assets/js/c8bdc4df.d594a844.js rename to assets/js/c8bdc4df.3e4aebed.js index 1483aa045..f02304f5a 100644 --- a/assets/js/c8bdc4df.d594a844.js +++ b/assets/js/c8bdc4df.3e4aebed.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5316],{82513:(e,a,o)=>{o.r(a),o.d(a,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>r,metadata:()=>n,toc:()=>p});var t=o(58168),i=(o(96540),o(15680));o(67443);const r={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},l=void 0,n={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},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:a,...o}=e;return(0,i.yg)(d,(0,t.A)({},u,o,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,i.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,i.yg)("h2",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,i.yg)("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.yg)("h2",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,i.yg)("p",null,"In order to use this, you must first be sure that the ",(0,i.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,i.yg)("p",null,"Simply add ",(0,i.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,i.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,i.yg)("h2",{id:"usage"},"Usage"),(0,i.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,i.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests."),(0,i.yg)("p",null,"See ",(0,i.yg)("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([[5316],{82513:(e,a,o)=>{o.r(a),o.d(a,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>r,metadata:()=>n,toc:()=>p});var t=o(58168),i=(o(96540),o(15680));o(67443);const r={id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},l=void 0,n={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},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:a,...o}=e;return(0,i.yg)(d,(0,t.A)({},u,o,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,i.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,i.yg)("h2",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,i.yg)("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.yg)("h2",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,i.yg)("p",null,"In order to use this, you must first be sure that the ",(0,i.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,i.yg)("p",null,"Simply add ",(0,i.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,i.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,i.yg)("h2",{id:"usage"},"Usage"),(0,i.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,i.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests."),(0,i.yg)("p",null,"See ",(0,i.yg)("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.7f0623e3.js b/assets/js/c933a311.fd1e7675.js similarity index 99% rename from assets/js/c933a311.7f0623e3.js rename to assets/js/c933a311.fd1e7675.js index 91abf10e3..ddf2f790e 100644 --- a/assets/js/c933a311.7f0623e3.js +++ b/assets/js/c933a311.fd1e7675.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6151],{19365:(e,t,n)=>{n.d(t,{A:()=>r});var a=n(96540),o=n(20053);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.A)(i.tabItem,r),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>N});var a=n(58168),o=n(96540),i=n(20053),r=n(23104),l=n(56347),s=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 m(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(!y({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]=h({queryString:n,groupId:a}),[d,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Dv)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=s??d;return y({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!y({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),m(e)}),[u,m,i]),tabValues:i}}var g=n(92303);const f={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,r.a_)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(d(t),s(a))},y=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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:y,onClick:p},r,{className:(0,i.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(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 w(e){const t=m(e);return o.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},o.createElement(b,(0,a.A)({},e,t)),o.createElement(v,(0,a.A)({},e,t)))}function N(e){const t=(0,g.A)();return o.createElement(w,(0,a.A)({key:String(t)},e))}},39454:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>p,frontMatter:()=>i,metadata:()=>l,toc:()=>u});var a=n(58168),o=(n(96540),n(15680));n(67443),n(11470),n(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.1/extend-type"},next:{title:"Input types",permalink:"/docs/6.1/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.yg)(d,(0,a.A)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.yg)("p",null,"For instance:"),(0,o.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,o.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.yg)("p",null,"GraphQLite allows you to use a ",(0,o.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!")," The ",(0,o.yg)("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.yg)("br",null),(0,o.yg)("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.yg)("p",null,"In methods with a ",(0,o.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.yg)("h2",{id:"sourcefield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.yg)("p",null,"If you don't want to rewrite all ",(0,o.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("h2",{id:"magicfield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"Any annotations described in the ",(0,o.yg)("a",{parentName:"p",href:"/docs/6.1/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/6.1/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.yg)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.yg)("pre",null,(0,o.yg)("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([[6151],{19365:(e,t,n)=>{n.d(t,{A:()=>r});var a=n(96540),o=n(20053);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.A)(i.tabItem,r),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>N});var a=n(58168),o=n(96540),i=n(20053),r=n(23104),l=n(56347),s=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 m(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(!y({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]=h({queryString:n,groupId:a}),[d,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,i]=(0,c.Dv)(n);return[a,(0,o.useCallback)((e=>{n&&i.set(e)}),[n,i])]}({groupId:a}),g=(()=>{const e=s??d;return y({value:e,tabValues:i})?e:null})();(0,o.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:r,selectValue:(0,o.useCallback)((e=>{if(!y({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),m(e)}),[u,m,i]),tabValues:i}}var g=n(92303);const f={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,r.a_)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(d(t),s(a))},y=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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:r}=e;return o.createElement("li",(0,a.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:y,onClick:p},r,{className:(0,i.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(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 w(e){const t=m(e);return o.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},o.createElement(b,(0,a.A)({},e,t)),o.createElement(v,(0,a.A)({},e,t)))}function N(e){const t=(0,g.A)();return o.createElement(w,(0,a.A)({key:String(t)},e))}},39454:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>p,frontMatter:()=>i,metadata:()=>l,toc:()=>u});var a=n(58168),o=(n(96540),n(15680));n(67443),n(11470),n(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.1/extend-type"},next:{title:"Input types",permalink:"/docs/6.1/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.yg)(d,(0,a.A)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,o.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,o.yg)("p",null,"For instance:"),(0,o.yg)("ul",null,(0,o.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,o.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,o.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,o.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,o.yg)("p",null,"GraphQLite allows you to use a ",(0,o.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,o.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,o.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,o.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,o.yg)("p",null,"The ",(0,o.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,o.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!")," The ",(0,o.yg)("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.yg)("br",null),(0,o.yg)("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.yg)("p",null,"In methods with a ",(0,o.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,o.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,o.yg)("h2",{id:"sourcefield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,o.yg)("p",null,"If you don't want to rewrite all ",(0,o.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,o.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,o.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,o.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,o.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,o.yg)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("h2",{id:"magicfield-annotation"},(0,o.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,o.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,o.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,o.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,o.yg)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,o.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,o.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,o.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,o.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"Any annotations described in the ",(0,o.yg)("a",{parentName:"p",href:"/docs/6.1/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/6.1/field-middlewares"},'"field middleware"')," can be used in the ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,o.yg)("div",{class:"alert alert--warning"},(0,o.yg)("strong",null,"Heads up!"),' The "annotation" attribute in @SourceField and @MagicField is only available as a ',(0,o.yg)("strong",null,"Doctrine annotations"),". You cannot use it in PHP 8 attributes (because PHP 8 attributes cannot be nested)"),(0,o.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,o.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,o.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,o.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,o.yg)("pre",null,(0,o.yg)("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.06ab14fb.js b/assets/js/c953ec08.be3c3152.js similarity index 99% rename from assets/js/c953ec08.06ab14fb.js rename to assets/js/c953ec08.be3c3152.js index a8db8f61b..b2c5c5a55 100644 --- a/assets/js/c953ec08.06ab14fb.js +++ b/assets/js/c953ec08.be3c3152.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5011],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(o.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>A});var n=a(58168),r=a(96540),o=a(20053),u=a(23104),l=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(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 T(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},r.createElement(g,(0,n.A)({},e,t)),r.createElement(y,(0,n.A)({},e,t)))}function A(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},74229:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),o=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(m,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, mutations are created ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/queries"},"like queries"),"."),(0,r.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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([[5011],{19365:(e,t,a)=>{a.d(t,{A:()=>u});var n=a(96540),r=a(20053);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.A)(o.tabItem,u),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>A});var n=a(58168),r=a(96540),o=a(20053),u=a(23104),l=a(56347),s=a(57485),i=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":a},t)},i.map((e=>{let{value:t,label:a,attributes:u}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",v.tabItem,u?.className,{"tabs__item--active":l===t})}),a??t)})))}function y(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 T(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",v.tabList)},r.createElement(g,(0,n.A)({},e,t)),r.createElement(y,(0,n.A)({},e,t)))}function A(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},74229:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>b,frontMatter:()=>l,metadata:()=>i,toc:()=>d});var n=a(58168),r=(a(96540),a(15680)),o=(a(67443),a(11470)),u=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(m,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, mutations are created ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/queries"},"like queries"),"."),(0,r.yg)("p",null,"To create a mutation, you must annotate a method in a controller with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.b6a13eda.js b/assets/js/ca36df4d.61047158.js similarity index 99% rename from assets/js/ca36df4d.b6a13eda.js rename to assets/js/ca36df4d.61047158.js index 140dc1d95..e8d190499 100644 --- a/assets/js/ca36df4d.b6a13eda.js +++ b/assets/js/ca36df4d.61047158.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2674],{81316:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>r,default:()=>u,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var t=n(58168),i=(n(96540),n(15680));n(67443);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"changelog",title:"Changelog",description:"8.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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/next/semver"}},p={},s=[{value:"8.0.0",id:"800",level:2},{value:"Breaking Changes",id:"breaking-changes",level:3},{value:"Improvements",id:"improvements",level:3},{value:"Bug Fixes",id:"bug-fixes",level:3},{value:"Minor Changes",id:"minor-changes",level:3},{value:"7.1.0",id:"710",level:2},{value:"Breaking Changes",id:"breaking-changes-1",level:3},{value:"Improvements",id:"improvements-1",level:3},{value:"7.0.0",id:"700",level:2},{value:"Breaking Changes",id:"breaking-changes-2",level:3},{value:"New Features",id:"new-features",level:3},{value:"Improvements",id:"improvements-2",level:3},{value:"Minor Changes",id:"minor-changes-1",level:3},{value:"6.2.3",id:"623",level:2},{value:"6.2.2",id:"622",level:2},{value:"6.2.1",id:"621",level:2},{value:"6.2.0",id:"620",level:2},{value:"6.1.0",id:"610",level:2},{value:"Breaking Changes",id:"breaking-changes-3",level:3},{value:"Improvements",id:"improvements-3",level:3},{value:"5.0.0",id:"500",level:2},{value:"Dependencies",id:"dependencies",level:3},{value:"4.3.0",id:"430",level:2},{value:"Breaking change",id:"breaking-change",level:3},{value:"Minor changes",id:"minor-changes-2",level:3},{value:"4.2.0",id:"420",level:2},{value:"Breaking change",id:"breaking-change-1",level:3},{value:"New features",id:"new-features-1",level:3},{value:"4.1.0",id:"410",level:2},{value:"Breaking change",id:"breaking-change-2",level:3},{value:"New features",id:"new-features-2",level:3},{value:"Minor changes",id:"minor-changes-3",level:3},{value:"Miscellaneous",id:"miscellaneous",level:3},{value:"4.0.0",id:"400",level:2},{value:"New features",id:"new-features-3",level:3},{value:"Symfony",id:"symfony",level:3},{value:"Laravel",id:"laravel",level:3},{value:"Internals",id:"internals",level:3}],d={toc:s},g="wrapper";function u(e){let{components:a,...n}=e;return(0,i.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"800"},"8.0.0"),(0,i.yg)("h3",{id:"breaking-changes"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/677"},"#677 Drops support for Doctrine annotations")," @fogrye")),(0,i.yg)("h3",{id:"improvements"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/668"},"#668 Adds working examples to docs")," @shish"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/698"},"#698 Performance optimizations and caching in development environments (",(0,i.yg)("inlineCode",{parentName:"a"},"devMode()"),")")," @oprypkhantc]")),(0,i.yg)("h3",{id:"bug-fixes"},"Bug Fixes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/702"},"#702 Fix prefetching for nested fields")," @sudevva")),(0,i.yg)("h3",{id:"minor-changes"},"Minor Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/695"},"#695 Removes dependecy to unmaintained thecodingmachine/cache-utils dependency")," @xyng"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/712"},"#712 Caching improvements with use of multiple ClassFinders")," @andrew-demb")),(0,i.yg)("h2",{id:"710"},"7.1.0"),(0,i.yg)("h3",{id:"breaking-changes-1"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#698 Removes some methods and classes, namely:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Deprecated ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::addControllerNamespace()")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::addTypeNamespace()")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::addNamespace()")),(0,i.yg)("li",{parentName:"ul"},"Deprecated ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setGlobTTL()")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::devMode()")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::prodMode()")),(0,i.yg)("li",{parentName:"ul"},"Removed ",(0,i.yg)("inlineCode",{parentName:"li"},"FactoryContext::get*TTL()")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperFactoryContext::get*TTL()")," as GraphQLite no longer uses TTLs to invalidate caches"),(0,i.yg)("li",{parentName:"ul"},"Removed ",(0,i.yg)("inlineCode",{parentName:"li"},"StaticClassListTypeMapper")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"ClassFinderTypeMapper")," used with ",(0,i.yg)("inlineCode",{parentName:"li"},"StaticClassFinder")),(0,i.yg)("li",{parentName:"ul"},"Renamed ",(0,i.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"ClassFinderTypeMapper")),(0,i.yg)("li",{parentName:"ul"},"Renamed ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setClassBoundCacheContractFactory()")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setClassBoundCache()"),",\n",(0,i.yg)("inlineCode",{parentName:"li"},"FactoryContext::getClassBoundCacheContractFactory()")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"FactoryContext::getClassBoundCache()")," and changed their signatures"),(0,i.yg)("li",{parentName:"ul"},"Removed ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperFactoryContext::getTypeNamespaces()")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperFactoryContext::getClassFinder()"))))),(0,i.yg)("h3",{id:"improvements-1"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#698 Performance optimizations and caching in development environments (",(0,i.yg)("inlineCode",{parentName:"li"},"devMode()"),"). @oprypkhantc")),(0,i.yg)("h2",{id:"700"},"7.0.0"),(0,i.yg)("h3",{id:"breaking-changes-2"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#664 Replaces ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/class-explorer"},"thecodingmachine/class-explorer")," with ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/alekitto/class-finder"},"kcs/class-finder")," resulting in the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setClassNameMapper")," being renamed to ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setFinder"),". This now expects an instance of ",(0,i.yg)("inlineCode",{parentName:"li"},"Kcs\\ClassFinder\\Finder")," instead of ",(0,i.yg)("inlineCode",{parentName:"li"},"Kcs\\ClassFinder\\Finder\\FinderInterface"),". @fogrye")),(0,i.yg)("h3",{id:"new-features"},"New Features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#649 Adds support for ",(0,i.yg)("inlineCode",{parentName:"li"},"subscription")," operations. @oojacoboo"),(0,i.yg)("li",{parentName:"ul"},"#612 Automatic query complexity analysis. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#611 Automatic persisted queries. @oprypkhantc")),(0,i.yg)("h3",{id:"improvements-2"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#658 Improves on prefetching for nested fields. @grynchuk"),(0,i.yg)("li",{parentName:"ul"},"#646 Improves exception handling during schema parsing. @fogrye"),(0,i.yg)("li",{parentName:"ul"},"#636 Allows the use of middleware on construtor params/fields. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#623 Improves support for description arguments on types/fields. @downace"),(0,i.yg)("li",{parentName:"ul"},"#628 Properly handles ",(0,i.yg)("inlineCode",{parentName:"li"},"@param")," annotations for generics support on field annotated constructor arguments. @oojacoboo"),(0,i.yg)("li",{parentName:"ul"},"#584 Immutability improvements across the codebase. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#588 Prefetch improvements. @oprpkhantc"),(0,i.yg)("li",{parentName:"ul"},"#606 Adds support for phpdoc descriptions and deprecation annotations on native enums. @mdoelker"),(0,i.yg)("li",{parentName:"ul"},"Thanks to @shish, @cvergne and @mshapovalov for updating the docs!")),(0,i.yg)("h3",{id:"minor-changes-1"},"Minor Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#639 Added support for Symfony 7. @janatjak")),(0,i.yg)("h2",{id:"623"},"6.2.3"),(0,i.yg)("p",null,"Adds support for ",(0,i.yg)("inlineCode",{parentName:"p"},"Psr\\Container")," 1.1 with #601"),(0,i.yg)("h2",{id:"622"},"6.2.2"),(0,i.yg)("p",null,"This is a very simple release. We support Doctrine annotation 1.x and we've deprecated ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory::setDoctrineAnnotationReader")," in favor of native PHP attributes."),(0,i.yg)("h2",{id:"621"},"6.2.1"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Added support for new ",(0,i.yg)("inlineCode",{parentName:"li"},"Void")," return types, allowing use of ",(0,i.yg)("inlineCode",{parentName:"li"},"void")," from operation resolvers. #574"),(0,i.yg)("li",{parentName:"ul"},"Improvements with authorization middleware #571"),(0,i.yg)("li",{parentName:"ul"},"Updated vendor dependencies: #580 #558")),(0,i.yg)("h2",{id:"620"},"6.2.0"),(0,i.yg)("p",null,"Lots of little nuggets in this release! We're now targeting PHP ^8.1 and have testing on 8.2."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Better support for union types and enums: #530, #535, #561, #570"),(0,i.yg)("li",{parentName:"ul"},"Various bug and interface fixes: #532, #575, #564"),(0,i.yg)("li",{parentName:"ul"},"GraphQL v15 required: #542"),(0,i.yg)("li",{parentName:"ul"},"Lots of codebase improvements, more strict typing: #548")),(0,i.yg)("p",null,"A special thanks to @rusted-love and @oprypkhantc for their contributions."),(0,i.yg)("h2",{id:"610"},"6.1.0"),(0,i.yg)("p",null,"A shoutout to @bladl for his work on this release, improving the code for better typing and PHP 8.0 syntax updates!"),(0,i.yg)("h3",{id:"breaking-changes-3"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#518 PSR-11 support now requires version 2"),(0,i.yg)("li",{parentName:"ul"},"#508 Due to some of the code improvements, additional typing has been added to some interfaces/classes. For instance, ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface::toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface::toGraphQLInputType")," now have the following signatures:")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"}," /**\n * @param (OutputType&GraphQLType)|null $subType\n *\n * @return OutputType&GraphQLType\n */\n public function toGraphQLOutputType(\n Type $type,\n OutputType|null $subType,\n ReflectionMethod|ReflectionProperty $reflector,\n DocBlock $docBlockObj\n ): OutputType;\n\n /**\n * @param (InputType&GraphQLType)|null $subType\n *\n * @return InputType&GraphQLType\n */\n public function toGraphQLInputType(\n Type $type,\n InputType|null $subType,\n string $argumentName,\n ReflectionMethod|ReflectionProperty $reflector,\n DocBlock $docBlockObj\n ): InputType;\n")),(0,i.yg)("h3",{id:"improvements-3"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#510"),(0,i.yg)("li",{parentName:"ul"},"#508")),(0,i.yg)("h2",{id:"500"},"5.0.0"),(0,i.yg)("h3",{id:"dependencies"},"Dependencies"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.yg)("h2",{id:"430"},"4.3.0"),(0,i.yg)("h3",{id:"breaking-change"},"Breaking change"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The method ",(0,i.yg)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.yg)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.yg)("h3",{id:"minor-changes-2"},"Minor changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.yg)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h3",{id:"breaking-change-1"},"Breaking change"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h3",{id:"new-features-1"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/next/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Factory]"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Type]")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/input-types#input-attribute"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Logged]"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Right]"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Security]"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h3",{id:"breaking-change-2"},"Breaking change"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h3",{id:"new-features-2"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h3",{id:"minor-changes-3"},"Minor changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h3",{id:"miscellaneous"},"Miscellaneous"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h3",{id:"new-features-3"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"#[Type]")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Assertion]")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Security]")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[InjectUser]")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"#[Decorate]")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("h3",{id:"symfony"},"Symfony"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h3",{id:"laravel"},"Laravel"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/next/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h3",{id:"internals"},"Internals"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2674],{81316:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>r,default:()=>u,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var t=n(58168),i=(n(96540),n(15680));n(67443);const l={id:"changelog",title:"Changelog",sidebar_label:"Changelog"},r=void 0,o={unversionedId:"changelog",id:"changelog",title:"Changelog",description:"8.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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/next/semver"}},p={},s=[{value:"8.0.0",id:"800",level:2},{value:"Breaking Changes",id:"breaking-changes",level:3},{value:"Improvements",id:"improvements",level:3},{value:"Bug Fixes",id:"bug-fixes",level:3},{value:"Minor Changes",id:"minor-changes",level:3},{value:"7.1.0",id:"710",level:2},{value:"Breaking Changes",id:"breaking-changes-1",level:3},{value:"Improvements",id:"improvements-1",level:3},{value:"7.0.0",id:"700",level:2},{value:"Breaking Changes",id:"breaking-changes-2",level:3},{value:"New Features",id:"new-features",level:3},{value:"Improvements",id:"improvements-2",level:3},{value:"Minor Changes",id:"minor-changes-1",level:3},{value:"6.2.3",id:"623",level:2},{value:"6.2.2",id:"622",level:2},{value:"6.2.1",id:"621",level:2},{value:"6.2.0",id:"620",level:2},{value:"6.1.0",id:"610",level:2},{value:"Breaking Changes",id:"breaking-changes-3",level:3},{value:"Improvements",id:"improvements-3",level:3},{value:"5.0.0",id:"500",level:2},{value:"Dependencies",id:"dependencies",level:3},{value:"4.3.0",id:"430",level:2},{value:"Breaking change",id:"breaking-change",level:3},{value:"Minor changes",id:"minor-changes-2",level:3},{value:"4.2.0",id:"420",level:2},{value:"Breaking change",id:"breaking-change-1",level:3},{value:"New features",id:"new-features-1",level:3},{value:"4.1.0",id:"410",level:2},{value:"Breaking change",id:"breaking-change-2",level:3},{value:"New features",id:"new-features-2",level:3},{value:"Minor changes",id:"minor-changes-3",level:3},{value:"Miscellaneous",id:"miscellaneous",level:3},{value:"4.0.0",id:"400",level:2},{value:"New features",id:"new-features-3",level:3},{value:"Symfony",id:"symfony",level:3},{value:"Laravel",id:"laravel",level:3},{value:"Internals",id:"internals",level:3}],d={toc:s},g="wrapper";function u(e){let{components:a,...n}=e;return(0,i.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"800"},"8.0.0"),(0,i.yg)("h3",{id:"breaking-changes"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/677"},"#677 Drops support for Doctrine annotations")," @fogrye")),(0,i.yg)("h3",{id:"improvements"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/668"},"#668 Adds working examples to docs")," @shish"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/698"},"#698 Performance optimizations and caching in development environments (",(0,i.yg)("inlineCode",{parentName:"a"},"devMode()"),")")," @oprypkhantc]")),(0,i.yg)("h3",{id:"bug-fixes"},"Bug Fixes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/702"},"#702 Fix prefetching for nested fields")," @sudevva")),(0,i.yg)("h3",{id:"minor-changes"},"Minor Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/695"},"#695 Removes dependecy to unmaintained thecodingmachine/cache-utils dependency")," @xyng"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/graphqlite/pull/712"},"#712 Caching improvements with use of multiple ClassFinders")," @andrew-demb")),(0,i.yg)("h2",{id:"710"},"7.1.0"),(0,i.yg)("h3",{id:"breaking-changes-1"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#698 Removes some methods and classes, namely:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Deprecated ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::addControllerNamespace()")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::addTypeNamespace()")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::addNamespace()")),(0,i.yg)("li",{parentName:"ul"},"Deprecated ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setGlobTTL()")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::devMode()")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::prodMode()")),(0,i.yg)("li",{parentName:"ul"},"Removed ",(0,i.yg)("inlineCode",{parentName:"li"},"FactoryContext::get*TTL()")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperFactoryContext::get*TTL()")," as GraphQLite no longer uses TTLs to invalidate caches"),(0,i.yg)("li",{parentName:"ul"},"Removed ",(0,i.yg)("inlineCode",{parentName:"li"},"StaticClassListTypeMapper")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"ClassFinderTypeMapper")," used with ",(0,i.yg)("inlineCode",{parentName:"li"},"StaticClassFinder")),(0,i.yg)("li",{parentName:"ul"},"Renamed ",(0,i.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"ClassFinderTypeMapper")),(0,i.yg)("li",{parentName:"ul"},"Renamed ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setClassBoundCacheContractFactory()")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setClassBoundCache()"),",\n",(0,i.yg)("inlineCode",{parentName:"li"},"FactoryContext::getClassBoundCacheContractFactory()")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"FactoryContext::getClassBoundCache()")," and changed their signatures"),(0,i.yg)("li",{parentName:"ul"},"Removed ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperFactoryContext::getTypeNamespaces()")," in favor of ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperFactoryContext::getClassFinder()"))))),(0,i.yg)("h3",{id:"improvements-1"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#698 Performance optimizations and caching in development environments (",(0,i.yg)("inlineCode",{parentName:"li"},"devMode()"),"). @oprypkhantc")),(0,i.yg)("h2",{id:"700"},"7.0.0"),(0,i.yg)("h3",{id:"breaking-changes-2"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#664 Replaces ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/thecodingmachine/class-explorer"},"thecodingmachine/class-explorer")," with ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/alekitto/class-finder"},"kcs/class-finder")," resulting in the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setClassNameMapper")," being renamed to ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory::setFinder"),". This now expects an instance of ",(0,i.yg)("inlineCode",{parentName:"li"},"Kcs\\ClassFinder\\Finder")," instead of ",(0,i.yg)("inlineCode",{parentName:"li"},"Kcs\\ClassFinder\\Finder\\FinderInterface"),". @fogrye")),(0,i.yg)("h3",{id:"new-features"},"New Features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#649 Adds support for ",(0,i.yg)("inlineCode",{parentName:"li"},"subscription")," operations. @oojacoboo"),(0,i.yg)("li",{parentName:"ul"},"#612 Automatic query complexity analysis. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#611 Automatic persisted queries. @oprypkhantc")),(0,i.yg)("h3",{id:"improvements-2"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#658 Improves on prefetching for nested fields. @grynchuk"),(0,i.yg)("li",{parentName:"ul"},"#646 Improves exception handling during schema parsing. @fogrye"),(0,i.yg)("li",{parentName:"ul"},"#636 Allows the use of middleware on construtor params/fields. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#623 Improves support for description arguments on types/fields. @downace"),(0,i.yg)("li",{parentName:"ul"},"#628 Properly handles ",(0,i.yg)("inlineCode",{parentName:"li"},"@param")," annotations for generics support on field annotated constructor arguments. @oojacoboo"),(0,i.yg)("li",{parentName:"ul"},"#584 Immutability improvements across the codebase. @oprypkhantc"),(0,i.yg)("li",{parentName:"ul"},"#588 Prefetch improvements. @oprpkhantc"),(0,i.yg)("li",{parentName:"ul"},"#606 Adds support for phpdoc descriptions and deprecation annotations on native enums. @mdoelker"),(0,i.yg)("li",{parentName:"ul"},"Thanks to @shish, @cvergne and @mshapovalov for updating the docs!")),(0,i.yg)("h3",{id:"minor-changes-1"},"Minor Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#639 Added support for Symfony 7. @janatjak")),(0,i.yg)("h2",{id:"623"},"6.2.3"),(0,i.yg)("p",null,"Adds support for ",(0,i.yg)("inlineCode",{parentName:"p"},"Psr\\Container")," 1.1 with #601"),(0,i.yg)("h2",{id:"622"},"6.2.2"),(0,i.yg)("p",null,"This is a very simple release. We support Doctrine annotation 1.x and we've deprecated ",(0,i.yg)("inlineCode",{parentName:"p"},"SchemaFactory::setDoctrineAnnotationReader")," in favor of native PHP attributes."),(0,i.yg)("h2",{id:"621"},"6.2.1"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Added support for new ",(0,i.yg)("inlineCode",{parentName:"li"},"Void")," return types, allowing use of ",(0,i.yg)("inlineCode",{parentName:"li"},"void")," from operation resolvers. #574"),(0,i.yg)("li",{parentName:"ul"},"Improvements with authorization middleware #571"),(0,i.yg)("li",{parentName:"ul"},"Updated vendor dependencies: #580 #558")),(0,i.yg)("h2",{id:"620"},"6.2.0"),(0,i.yg)("p",null,"Lots of little nuggets in this release! We're now targeting PHP ^8.1 and have testing on 8.2."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Better support for union types and enums: #530, #535, #561, #570"),(0,i.yg)("li",{parentName:"ul"},"Various bug and interface fixes: #532, #575, #564"),(0,i.yg)("li",{parentName:"ul"},"GraphQL v15 required: #542"),(0,i.yg)("li",{parentName:"ul"},"Lots of codebase improvements, more strict typing: #548")),(0,i.yg)("p",null,"A special thanks to @rusted-love and @oprypkhantc for their contributions."),(0,i.yg)("h2",{id:"610"},"6.1.0"),(0,i.yg)("p",null,"A shoutout to @bladl for his work on this release, improving the code for better typing and PHP 8.0 syntax updates!"),(0,i.yg)("h3",{id:"breaking-changes-3"},"Breaking Changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#518 PSR-11 support now requires version 2"),(0,i.yg)("li",{parentName:"ul"},"#508 Due to some of the code improvements, additional typing has been added to some interfaces/classes. For instance, ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface::toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface::toGraphQLInputType")," now have the following signatures:")),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"}," /**\n * @param (OutputType&GraphQLType)|null $subType\n *\n * @return OutputType&GraphQLType\n */\n public function toGraphQLOutputType(\n Type $type,\n OutputType|null $subType,\n ReflectionMethod|ReflectionProperty $reflector,\n DocBlock $docBlockObj\n ): OutputType;\n\n /**\n * @param (InputType&GraphQLType)|null $subType\n *\n * @return InputType&GraphQLType\n */\n public function toGraphQLInputType(\n Type $type,\n InputType|null $subType,\n string $argumentName,\n ReflectionMethod|ReflectionProperty $reflector,\n DocBlock $docBlockObj\n ): InputType;\n")),(0,i.yg)("h3",{id:"improvements-3"},"Improvements"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"#510"),(0,i.yg)("li",{parentName:"ul"},"#508")),(0,i.yg)("h2",{id:"500"},"5.0.0"),(0,i.yg)("h3",{id:"dependencies"},"Dependencies"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.yg)("h2",{id:"430"},"4.3.0"),(0,i.yg)("h3",{id:"breaking-change"},"Breaking change"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The method ",(0,i.yg)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.yg)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.yg)("h3",{id:"minor-changes-2"},"Minor changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.yg)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h3",{id:"breaking-change-1"},"Breaking change"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h3",{id:"new-features-1"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/next/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Factory]"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Type]")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/input-types#input-attribute"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Logged]"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Right]"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Security]"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h3",{id:"breaking-change-2"},"Breaking change"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h3",{id:"new-features-2"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h3",{id:"minor-changes-3"},"Minor changes"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h3",{id:"miscellaneous"},"Miscellaneous"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h3",{id:"new-features-3"},"New features"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"#[Type]")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Assertion]")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Security]")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[InjectUser]")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"#[Decorate]")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("h3",{id:"symfony"},"Symfony"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h3",{id:"laravel"},"Laravel"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/next/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h3",{id:"internals"},"Internals"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/caa79efa.24eb6a09.js b/assets/js/caa79efa.000a052a.js similarity index 99% rename from assets/js/caa79efa.24eb6a09.js rename to assets/js/caa79efa.000a052a.js index 69d3d415d..54e8f64bc 100644 --- a/assets/js/caa79efa.24eb6a09.js +++ b/assets/js/caa79efa.000a052a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9062],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),i=a(89466);function y(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??y(a);return function(e){const t=(0,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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(!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}),[y,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=s??y;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:y}=(0,o.a_)(),c=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(y(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":c(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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:c},o,{className:(0,p.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},29450:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>y});var n=a(58168),r=(a(96540),a(15680)),p=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],c={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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([[9062],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),i=a(89466);function y(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??y(a);return function(e){const t=(0,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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(!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}),[y,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=s??y;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:y}=(0,o.a_)(),c=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(y(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":c(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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:c},o,{className:(0,p.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},29450:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>y});var n=a(58168),r=(a(96540),a(15680)),p=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],c={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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.be2bef33.js b/assets/js/cb01db44.29ddbf91.js similarity index 99% rename from assets/js/cb01db44.be2bef33.js rename to assets/js/cb01db44.29ddbf91.js index 0b2a2c9f4..5cb8d5e12 100644 --- a/assets/js/cb01db44.be2bef33.js +++ b/assets/js/cb01db44.29ddbf91.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8703],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var t=a(96540),r=a(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),l=a(20053),i=a(23104),s=a(56347),p=a(57485),c=a(31682),o=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function m(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function d(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function y(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[p,c]=g({queryString:a,groupId:t}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{h&&s(h)}),[h]);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),y(e)}),[c,y,l]),tabValues:l}}var h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=c[a].value;t!==s&&(u(n),p(t))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return r.createElement("li",(0,t.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function N(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(v,(0,t.A)({},e,n)))}function T(e){const n=(0,h.A)();return r.createElement(N,(0,t.A)({key:String(n)},e))}},49784:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>g,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var t=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...a}=e;return(0,r.yg)(d,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.yg)("p",null,"Written in ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.yg)("p",null,"The GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.yg)("p",null,"This will translate in GraphQL schema as:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.yg)("p",null,"Please note that you do not need to put the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.yg)("p",null,"You don't have to explicitly put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8703],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var t=a(96540),r=a(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),l=a(20053),i=a(23104),s=a(56347),p=a(57485),c=a(31682),o=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function m(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function d(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function y(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[p,c]=g({queryString:a,groupId:t}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{h&&s(h)}),[h]);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),y(e)}),[c,y,l]),tabValues:l}}var h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=c[a].value;t!==s&&(u(n),p(t))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return r.createElement("li",(0,t.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function N(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(v,(0,t.A)({},e,n)))}function T(e){const n=(0,h.A)();return r.createElement(N,(0,t.A)({key:String(n)},e))}},49784:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>g,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var t=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...a}=e;return(0,r.yg)(d,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.yg)("p",null,"Written in ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.yg)("p",null,"The GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.yg)("p",null,"This will translate in GraphQL schema as:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.yg)("p",null,"Please note that you do not need to put the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.yg)("p",null,"You don't have to explicitly put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/cc08685c.99b4e529.js b/assets/js/cc08685c.24227d4e.js similarity index 99% rename from assets/js/cc08685c.99b4e529.js rename to assets/js/cc08685c.24227d4e.js index 239ae0f35..ee2f5a796 100644 --- a/assets/js/cc08685c.99b4e529.js +++ b/assets/js/cc08685c.24227d4e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5515],{604:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/4.2/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5515],{604:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/4.2/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/cc1c02fe.8c3dea08.js b/assets/js/cc1c02fe.88a58c68.js similarity index 99% rename from assets/js/cc1c02fe.8c3dea08.js rename to assets/js/cc1c02fe.88a58c68.js index 29592e020..2c772431c 100644 --- a/assets/js/cc1c02fe.8c3dea08.js +++ b/assets/js/cc1c02fe.88a58c68.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7492],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),r=n(20053);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.A)(o.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),o=n(20053),i=n(23104),l=n(56347),s=n(57485),u=n(31682),c=n(89466);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,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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,u]=m({queryString:n,groupId:a}),[p,h]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,c.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),y=(()=>{const e=s??p;return g({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(p(t),s(a))},g=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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},i,{className:(0,o.A)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(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 P(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",b.tabList)},r.createElement(f,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,y.A)();return r.createElement(P,(0,a.A)({key:String(t)},e))}},27796:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),o=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...n}=e;return(0,r.yg)(g,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"Please note that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("strong",null,"Heads up!"),(0,r.yg)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",null,"PhpStorm via the ",(0,r.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.yg)("li",null,"Eclipse via the ",(0,r.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.yg)("li",null,"Netbeans has native support")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.yg)("p",null,"The same code can be written this way:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.yg)("p",null,"They support the same attributes too."),(0,r.yg)("p",null,"A few notable differences:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.yg)("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.yg)("p",null,"Let's take an example with the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/autowiring"},(0,r.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7492],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),r=n(20053);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.A)(o.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),o=n(20053),i=n(23104),l=n(56347),s=n(57485),u=n(31682),c=n(89466);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,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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,u]=m({queryString:n,groupId:a}),[p,h]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,c.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),y=(()=>{const e=s??p;return g({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(p(t),s(a))},g=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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},i,{className:(0,o.A)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(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 P(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",b.tabList)},r.createElement(f,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,y.A)();return r.createElement(P,(0,a.A)({key:String(t)},e))}},27796:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),o=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...n}=e;return(0,r.yg)(g,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"Please note that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("strong",null,"Heads up!"),(0,r.yg)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",null,"PhpStorm via the ",(0,r.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.yg)("li",null,"Eclipse via the ",(0,r.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.yg)("li",null,"Netbeans has native support")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.yg)("p",null,"The same code can be written this way:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.yg)("p",null,"They support the same attributes too."),(0,r.yg)("p",null,"A few notable differences:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.yg)("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.yg)("p",null,"Let's take an example with the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.3/autowiring"},(0,r.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/cc1f18af.9d430517.js b/assets/js/cc1f18af.cf44e18c.js similarity index 99% rename from assets/js/cc1f18af.9d430517.js rename to assets/js/cc1f18af.cf44e18c.js index 0df33904a..c29d12a99 100644 --- a/assets/js/cc1f18af.9d430517.js +++ b/assets/js/cc1f18af.cf44e18c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3177],{56970:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function u(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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([[3177],{56970:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function u(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},'$ php artisan vendor:publish --provider="TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider"\n')),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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.a0197dfd.js b/assets/js/cd25a595.98e47423.js similarity index 99% rename from assets/js/cd25a595.a0197dfd.js rename to assets/js/cd25a595.98e47423.js index 3b0d100e4..6b4dfe6fe 100644 --- a/assets/js/cd25a595.a0197dfd.js +++ b/assets/js/cd25a595.98e47423.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2113],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),u=a(56347),i=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),g=(()=>{const e=i??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&u(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}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var g=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},26183:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},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.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.yg)("p",null,"You must start by installing this package:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.yg)("p",null,"In order to use this, you must first be sure that the ",(0,r.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.yg)("pre",null,(0,r.yg)("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([[2113],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),u=a(56347),i=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),g=(()=>{const e=i??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&u(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}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var g=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},26183:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},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.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.yg)("p",null,"You must start by installing this package:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.yg)("p",null,"In order to use this, you must first be sure that the ",(0,r.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.yg)("pre",null,(0,r.yg)("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.09caf28c.js b/assets/js/cd30f404.91835414.js similarity index 99% rename from assets/js/cd30f404.09caf28c.js rename to assets/js/cd30f404.91835414.js index 28d8a1c47..b6fc1dc3f 100644 --- a/assets/js/cd30f404.09caf28c.js +++ b/assets/js/cd30f404.91835414.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9661],{19365:(e,a,n)=>{n.d(a,{A:()=>i});var t=n(96540),r=n(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:a,hidden:n,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:n},a)}},11470:(e,a,n)=>{n.d(a,{A:()=>P});var t=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),p=n(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:n,attributes:t,default:r}}=e;return{value:a,label:n,attributes:t,default:r}}))}function d(e){const{values:a,children:n}=e;return(0,r.useMemo)((()=>{const e=a??c(n);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,n])}function g(e){let{value:a,tabValues:n}=e;return n.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:n}=e;const t=(0,o.W6)(),l=function(e){let{queryString:a=!1,groupId:n}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:n});return[(0,s.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(t.location.search);a.set(l,e),t.replace({...t.location,search:a.toString()})}),[l,t])]}function m(e){const{defaultValue:a,queryString:n=!1,groupId:t}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const t=n.find((e=>e.default))??n[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:a,tabValues:l}))),[s,u]=h({queryString:n,groupId:t}),[c,m]=function(e){let{groupId:a}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(a),[t,l]=(0,p.Dv)(n);return[t,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:t}),y=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,l]),tabValues:l}}var y=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const a=e.currentTarget,n=p.indexOf(a),t=u[n].value;t!==o&&(c(a),s(t))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;a=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;a=p[n]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":n},a)},u.map((e=>{let{value:a,label:n,attributes:i}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===a})}),n??a)})))}function b(e){let{lazy:a,children:n,selectedValue:t}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(a){const e=l.find((e=>e.props.value===t));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==t}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(v,(0,t.A)({},e,a)),r.createElement(b,(0,t.A)({},e,a)))}function P(e){const a=(0,y.A)();return r.createElement(w,(0,t.A)({key:String(a)},e))}},6638:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var t=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},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},g="wrapper";function h(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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([[9661],{19365:(e,a,n)=>{n.d(a,{A:()=>i});var t=n(96540),r=n(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:a,hidden:n,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:n},a)}},11470:(e,a,n)=>{n.d(a,{A:()=>P});var t=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),p=n(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:n,attributes:t,default:r}}=e;return{value:a,label:n,attributes:t,default:r}}))}function d(e){const{values:a,children:n}=e;return(0,r.useMemo)((()=>{const e=a??c(n);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,n])}function g(e){let{value:a,tabValues:n}=e;return n.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:n}=e;const t=(0,o.W6)(),l=function(e){let{queryString:a=!1,groupId:n}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:n});return[(0,s.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(t.location.search);a.set(l,e),t.replace({...t.location,search:a.toString()})}),[l,t])]}function m(e){const{defaultValue:a,queryString:n=!1,groupId:t}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const t=n.find((e=>e.default))??n[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:a,tabValues:l}))),[s,u]=h({queryString:n,groupId:t}),[c,m]=function(e){let{groupId:a}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(a),[t,l]=(0,p.Dv)(n);return[t,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:t}),y=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,l]),tabValues:l}}var y=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const a=e.currentTarget,n=p.indexOf(a),t=u[n].value;t!==o&&(c(a),s(t))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;a=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;a=p[n]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":n},a)},u.map((e=>{let{value:a,label:n,attributes:i}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===a})}),n??a)})))}function b(e){let{lazy:a,children:n,selectedValue:t}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(a){const e=l.find((e=>e.props.value===t));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==t}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(v,(0,t.A)({},e,a)),r.createElement(b,(0,t.A)({},e,a)))}function P(e){const a=(0,y.A)();return r.createElement(w,(0,t.A)({key:String(a)},e))}},6638:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var t=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},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},g="wrapper";function h(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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/cd699560.a312a130.js b/assets/js/cd699560.60280a86.js similarity index 99% rename from assets/js/cd699560.a312a130.js rename to assets/js/cd699560.60280a86.js index e4ce12ee7..ce8483933 100644 --- a/assets/js/cd699560.a312a130.js +++ b/assets/js/cd699560.60280a86.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5281],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),r=n(20053);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.A)(o.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),o=n(20053),i=n(23104),l=n(56347),s=n(57485),u=n(31682),c=n(89466);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,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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,u]=m({queryString:n,groupId:a}),[p,h]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,c.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),y=(()=>{const e=s??p;return g({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(p(t),s(a))},g=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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},i,{className:(0,o.A)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(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 P(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",b.tabList)},r.createElement(f,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,y.A)();return r.createElement(P,(0,a.A)({key:String(t)},e))}},31017:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),o=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...n}=e;return(0,r.yg)(g,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"Please note that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("strong",null,"Heads up!"),(0,r.yg)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",null,"PhpStorm via the ",(0,r.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.yg)("li",null,"Eclipse via the ",(0,r.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.yg)("li",null,"Netbeans has native support")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.yg)("p",null,"The same code can be written this way:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.yg)("p",null,"They support the same attributes too."),(0,r.yg)("p",null,"A few notable differences:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.yg)("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.yg)("p",null,"Let's take an example with the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/autowiring"},(0,r.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5281],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),r=n(20053);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.A)(o.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),o=n(20053),i=n(23104),l=n(56347),s=n(57485),u=n(31682),c=n(89466);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,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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,u]=m({queryString:n,groupId:a}),[p,h]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,c.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),y=(()=>{const e=s??p;return g({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(e){let{className:t,block:n,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(p(t),s(a))},g=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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},i,{className:(0,o.A)("tabs__item",b.tabItem,i?.className,{"tabs__item--active":l===t})}),n??t)})))}function v(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 P(e){const t=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",b.tabList)},r.createElement(f,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,y.A)();return r.createElement(P,(0,a.A)({key:String(t)},e))}},31017:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),o=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...n}=e;return(0,r.yg)(g,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"Please note that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("strong",null,"Heads up!"),(0,r.yg)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",null,"PhpStorm via the ",(0,r.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.yg)("li",null,"Eclipse via the ",(0,r.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.yg)("li",null,"Netbeans has native support")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.yg)("p",null,"The same code can be written this way:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.yg)("p",null,"They support the same attributes too."),(0,r.yg)("p",null,"A few notable differences:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.yg)("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.yg)("p",null,"Let's take an example with the ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.2/autowiring"},(0,r.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/cddcd4e6.18a539ee.js b/assets/js/cddcd4e6.37e96033.js similarity index 99% rename from assets/js/cddcd4e6.18a539ee.js rename to assets/js/cddcd4e6.37e96033.js index 1e4995395..768bdc4e6 100644 --- a/assets/js/cddcd4e6.18a539ee.js +++ b/assets/js/cddcd4e6.37e96033.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4116],{19365:(e,n,t)=>{t.d(n,{A:()=>u});var a=t(96540),l=t(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:n,hidden:t,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),l=t(96540),r=t(20053),u=t(23104),o=t(56347),i=t(57485),s=t(31682),c=t(89466);function m(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.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:l}}=e;return{value:n,label:t,attributes:a,default:l}}))}function p(e){const{values:n,children:t}=e;return(0,l.useMemo)((()=>{const e=n??m(t);return function(e){const n=(0,s.X)(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 g(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:t}=e;const a=(0,o.W6)(),r=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.aZ)(r),(0,l.useCallback)((e=>{if(!r)return;const n=new URLSearchParams(a.location.search);n.set(r,e),a.replace({...a.location,search:n.toString()})}),[r,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,r=p(e),[u,o]=(0,l.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(!g({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:r}))),[i,s]=d({queryString:t,groupId:a}),[m,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,r]=(0,c.Dv)(t);return[a,(0,l.useCallback)((e=>{t&&r.set(e)}),[t,r])]}({groupId:a}),h=(()=>{const e=i??m;return g({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!g({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),y(e)}),[s,y,r]),tabValues:r}}var h=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:m}=(0,u.a_)(),p=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==o&&(m(n),i(a))},g=e=>{let n=null;switch(e.key){case"Enter":p(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 l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:u}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>c.push(e),onKeyDown:g,onClick:p},u,{className:(0,r.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const r=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,l.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function q(e){const n=y(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,n)),l.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(n)},e))}},89848:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>m});var a=t(58168),l=(t(96540),t(15680)),r=(t(67443),t(11470)),u=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"}},c={},m=[{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}],p={toc:m},g="wrapper";function d(e){let{components:n,...t}=e;return(0,l.yg)(g,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.yg)("p",null,"By settings ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.yg)("p",null,"The mutation below will log-in a user:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.yg)("p",null,"In Symfony, user objects implement ",(0,l.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.yg)("p",null,"If you want to get more fields, just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"You can now query this field using an ",(0,l.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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")))))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4116],{19365:(e,n,t)=>{t.d(n,{A:()=>u});var a=t(96540),l=t(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:n,hidden:t,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>N});var a=t(58168),l=t(96540),r=t(20053),u=t(23104),o=t(56347),i=t(57485),s=t(31682),c=t(89466);function m(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.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:l}}=e;return{value:n,label:t,attributes:a,default:l}}))}function p(e){const{values:n,children:t}=e;return(0,l.useMemo)((()=>{const e=n??m(t);return function(e){const n=(0,s.X)(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 g(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:t}=e;const a=(0,o.W6)(),r=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.aZ)(r),(0,l.useCallback)((e=>{if(!r)return;const n=new URLSearchParams(a.location.search);n.set(r,e),a.replace({...a.location,search:n.toString()})}),[r,a])]}function y(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,r=p(e),[u,o]=(0,l.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(!g({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:r}))),[i,s]=d({queryString:t,groupId:a}),[m,y]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,r]=(0,c.Dv)(t);return[a,(0,l.useCallback)((e=>{t&&r.set(e)}),[t,r])]}({groupId:a}),h=(()=>{const e=i??m;return g({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);return{selectedValue:u,selectValue:(0,l.useCallback)((e=>{if(!g({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),y(e)}),[s,y,r]),tabValues:r}}var h=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:m}=(0,u.a_)(),p=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==o&&(m(n),i(a))},g=e=>{let n=null;switch(e.key){case"Enter":p(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 l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:u}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===n?0:-1,"aria-selected":o===n,key:n,ref:e=>c.push(e),onKeyDown:g,onClick:p},u,{className:(0,r.A)("tabs__item",f.tabItem,u?.className,{"tabs__item--active":o===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const r=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,l.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function q(e){const n=y(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,n)),l.createElement(v,(0,a.A)({},e,n)))}function N(e){const n=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(n)},e))}},89848:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>m});var a=t(58168),l=(t(96540),t(15680)),r=(t(67443),t(11470)),u=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"}},c={},m=[{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}],p={toc:m},g="wrapper";function d(e){let{components:n,...t}=e;return(0,l.yg)(g,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony."),(0,l.yg)("h2",{id:"login-and-logout"},"Login and logout"),(0,l.yg)("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.yg)("p",null,'If you need to customize this behaviour, you can edit the "graphqlite.security" configuration key.'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: auto # Default setting\n enable_me: auto # Default setting\n")),(0,l.yg)("p",null,'By default, GraphQLite will enable "login" and "logout" mutations and the "me" query if the following conditions are met:'),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},'the "security" bundle is installed and configured (with a security provider and encoder)'),(0,l.yg)("li",{parentName:"ul"},'the "session" support is enabled (via the "framework.session.enabled" key).')),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: on\n")),(0,l.yg)("p",null,"By settings ",(0,l.yg)("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.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n enable_login: off\n")),(0,l.yg)("p",null,"Use the ",(0,l.yg)("inlineCode",{parentName:"p"},"enable_login=off")," to disable the mutations."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n firewall_name: main # default value\n")),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"graphqlite.security.firewall_name"),"."),(0,l.yg)("h2",{id:"schema-and-request-security"},"Schema and request security"),(0,l.yg)("p",null,"You can disable the introspection of your GraphQL API (for instance in production mode) using\nthe ",(0,l.yg)("inlineCode",{parentName:"p"},"introspection")," configuration properties."),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n introspection: false\n")),(0,l.yg)("p",null,"You can set the maximum complexity and depth of your GraphQL queries using the ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_complexity"),"\nand ",(0,l.yg)("inlineCode",{parentName:"p"},"maximum_query_depth")," configuration properties"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-yaml"},"graphqlite:\n security:\n maximum_query_complexity: 314\n maximum_query_depth: 42\n")),(0,l.yg)("h3",{id:"login-using-the-login-mutation"},'Login using the "login" mutation'),(0,l.yg)("p",null,"The mutation below will log-in a user:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},'mutation login {\n login(userName:"foo", password:"bar") {\n userName\n roles\n }\n}\n')),(0,l.yg)("h3",{id:"get-the-current-user-with-the-me-query"},'Get the current user with the "me" query'),(0,l.yg)("p",null,'Retrieving the current user is easy with the "me" query:'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n }\n}\n")),(0,l.yg)("p",null,"In Symfony, user objects implement ",(0,l.yg)("inlineCode",{parentName:"p"},"Symfony\\Component\\Security\\Core\\User\\UserInterface"),".\nThis interface is automatically mapped to a type with 2 fields:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"userName: String!")),(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"roles: [String!]!"))),(0,l.yg)("p",null,"If you want to get more fields, just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation to your user class:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"You can now query this field using an ",(0,l.yg)("a",{parentName:"p",href:"https://graphql.org/learn/queries/#inline-fragments"},"inline fragment"),":"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n me {\n userName\n roles\n ... on User {\n email\n }\n }\n}\n")),(0,l.yg)("h3",{id:"logout-using-the-logout-mutation"},'Logout using the "logout" mutation'),(0,l.yg)("p",null,'Use the "logout" mutation to log a user out'),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-graphql"},"mutation logout {\n logout\n}\n")),(0,l.yg)("h2",{id:"injecting-the-request"},"Injecting the Request"),(0,l.yg)("p",null,"You can inject the Symfony Request object in any query/mutation/field."),(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(u.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(u.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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")))))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/ce95b17c.1a9c939a.js b/assets/js/ce95b17c.086e4223.js similarity index 98% rename from assets/js/ce95b17c.1a9c939a.js rename to assets/js/ce95b17c.086e4223.js index 1e390e2cf..5a2d69ca0 100644 --- a/assets/js/ce95b17c.1a9c939a.js +++ b/assets/js/ce95b17c.086e4223.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4e3],{90428:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>o,default:()=>h,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var a=t(58168),r=(t(96540),t(15680));t(67443);const l={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},o=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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},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:n,...t}=e;return(0,r.yg)(d,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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([[4e3],{90428:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>o,default:()=>h,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var a=t(58168),r=(t(96540),t(15680));t(67443);const l={id:"query-plan",title:"Query plan",sidebar_label:"Query plan"},o=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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},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:n,...t}=e;return(0,r.yg)(d,(0,a.A)({},p,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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/cf877cff.7ca61dac.js b/assets/js/cf877cff.27151cdf.js similarity index 97% rename from assets/js/cf877cff.7ca61dac.js rename to assets/js/cf877cff.27151cdf.js index 56012cb1f..a7c96a45d 100644 --- a/assets/js/cf877cff.7ca61dac.js +++ b/assets/js/cf877cff.27151cdf.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8177],{74259:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"version-7.0.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-7.0.0/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/7.0.0/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/getting-started.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"docs",previous:{title:"GraphQLite",permalink:"/docs/7.0.0/"},next:{title:"Symfony bundle",permalink:"/docs/7.0.0/symfony-bundle"}},d={},l=[],c={toc:l},g="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,r.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8177],{74259:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);const n={id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},o=void 0,s={unversionedId:"getting-started",id:"version-7.0.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-7.0.0/getting-started.md",sourceDirName:".",slug:"/getting-started",permalink:"/docs/7.0.0/getting-started",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/getting-started.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"docs",previous:{title:"GraphQLite",permalink:"/docs/7.0.0/"},next:{title:"Symfony bundle",permalink:"/docs/7.0.0/symfony-bundle"}},d={},l=[],c={toc:l},g="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,r.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/7.0.0/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d07ad772.d0f77da4.js b/assets/js/d07ad772.e7609360.js similarity index 99% rename from assets/js/d07ad772.d0f77da4.js rename to assets/js/d07ad772.e7609360.js index c0ea822ae..142ea5baf 100644 --- a/assets/js/d07ad772.d0f77da4.js +++ b/assets/js/d07ad772.e7609360.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4103],{80773:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function u(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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([[4103],{80773:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>u,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:s},h="wrapper";function u(e){let{components:a,...n}=e;return(0,r.yg)(h,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The GraphQLite-Laravel package is compatible with ",(0,r.yg)("strong",{parentName:"p"},"Laravel 5.7+"),", ",(0,r.yg)("strong",{parentName:"p"},"Laravel 6.x")," and ",(0,r.yg)("strong",{parentName:"p"},"Laravel 7.x"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-laravel\n")),(0,r.yg)("p",null,"If you want to publish the configuration (in order to edit it), run:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ php artisan vendor:publish --provider=TheCodingMachine\\GraphQLite\\Laravel\\Providers\\GraphQLiteServiceProvider\n")),(0,r.yg)("p",null,"You can then configure the library by editing ",(0,r.yg)("inlineCode",{parentName:"p"},"config/graphqlite.php"),"."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The debug parameters are detailed in the ",(0,r.yg)("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.yg)("h2",{id:"configuring-csrf-protection"},"Configuring CSRF protection"),(0,r.yg)("div",{class:"alert alert--warning"},"By default, the ",(0,r.yg)("code",null,"/graphql")," route is placed under ",(0,r.yg)("code",null,"web")," middleware group which requires a",(0,r.yg)("a",{href:"https://laravel.com/docs/6.x/csrf"},"CSRF token"),"."),(0,r.yg)("p",null,"You have 3 options:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Use the ",(0,r.yg)("inlineCode",{parentName:"li"},"api")," middleware"),(0,r.yg)("li",{parentName:"ul"},"Disable CSRF for GraphQL routes"),(0,r.yg)("li",{parentName:"ul"},"or configure your GraphQL client to pass the ",(0,r.yg)("inlineCode",{parentName:"li"},"X-CSRF-TOKEN")," with every GraphQL query")),(0,r.yg)("h3",{id:"use-the-api-middleware"},"Use the ",(0,r.yg)("inlineCode",{parentName:"h3"},"api")," middleware"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"api")," middleware instead of the ",(0,r.yg)("inlineCode",{parentName:"p"},"web")," middleware:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php",metastring:'title="config/graphqlite.php"',title:'"config/graphqlite.php"'}," ['api'],\n 'guard' => ['api'],\n];\n")),(0,r.yg)("h3",{id:"disable-csrf-for-the-graphql-route"},"Disable CSRF for the /graphql route"),(0,r.yg)("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.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"graphql")," to ",(0,r.yg)("inlineCode",{parentName:"p"},"$except")," in ",(0,r.yg)("inlineCode",{parentName:"p"},"app/Http/Middleware/VerifyCsrfToken.php"),"."),(0,r.yg)("h3",{id:"configuring-your-graphql-client"},"Configuring your GraphQL client"),(0,r.yg)("p",null,"If you are planning to use ",(0,r.yg)("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.yg)("p",null,"The way you do this depends on the Javascript GraphQL client you are using."),(0,r.yg)("p",null,"Assuming you are using ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"adding-graphql-devtools"},"Adding GraphQL DevTools"),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/mll-lab/laravel-graphql-playground"},"GraphQL Playground")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require mll-lab/laravel-graphql-playground\n")),(0,r.yg)("p",null,"By default, the playground will be available at ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql-playground"),"."),(0,r.yg)("p",null,"Or you can install ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/XKojiMedia/laravel-altair-graphql"},"Altair GraphQL Client")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require xkojimedia/laravel-altair-graphql\n")),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"'/graphql'")," by default)."),(0,r.yg)("h2",{id:"troubleshooting-http-419-errors"},"Troubleshooting HTTP 419 errors"),(0,r.yg)("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.yg)("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.221c7e6d.js b/assets/js/d3540d59.fa61907b.js similarity index 99% rename from assets/js/d3540d59.221c7e6d.js rename to assets/js/d3540d59.fa61907b.js index 7bb41dde6..9941b7f55 100644 --- a/assets/js/d3540d59.221c7e6d.js +++ b/assets/js/d3540d59.fa61907b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4513],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var t=a(96540),r=a(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),l=a(20053),i=a(23104),s=a(56347),p=a(57485),c=a(31682),o=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function m(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function d(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function y(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[p,c]=g({queryString:a,groupId:t}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{h&&s(h)}),[h]);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),y(e)}),[c,y,l]),tabValues:l}}var h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=c[a].value;t!==s&&(u(n),p(t))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return r.createElement("li",(0,t.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function N(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(v,(0,t.A)({},e,n)))}function T(e){const n=(0,h.A)();return r.createElement(N,(0,t.A)({key:String(n)},e))}},49945:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>g,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var t=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...a}=e;return(0,r.yg)(d,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.yg)("p",null,"Written in ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.yg)("p",null,"The GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.yg)("p",null,"This will translate in GraphQL schema as:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.yg)("p",null,"Please note that you do not need to put the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.yg)("p",null,"You don't have to explicitly put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4513],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var t=a(96540),r=a(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),l=a(20053),i=a(23104),s=a(56347),p=a(57485),c=a(31682),o=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function m(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function d(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function y(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!d({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[p,c]=g({queryString:a,groupId:t}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=p??u;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{h&&s(h)}),[h]);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),y(e)}),[c,y,l]),tabValues:l}}var h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=c[a].value;t!==s&&(u(n),p(t))},d=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return r.createElement("li",(0,t.A)({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.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function N(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(v,(0,t.A)({},e,n)))}function T(e){const n=(0,h.A)();return r.createElement(N,(0,t.A)({key:String(n)},e))}},49945:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>g,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var t=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...a}=e;return(0,r.yg)(d,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.yg)("p",null,"Written in ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.yg)("p",null,"The GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.yg)("p",null,"This will translate in GraphQL schema as:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.yg)("p",null,"Please note that you do not need to put the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.yg)("p",null,"You don't have to explicitly put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d4446569.50b4e40c.js b/assets/js/d4446569.3cbc548f.js similarity index 99% rename from assets/js/d4446569.50b4e40c.js rename to assets/js/d4446569.3cbc548f.js index de6eab7dc..9764a75aa 100644 --- a/assets/js/d4446569.50b4e40c.js +++ b/assets/js/d4446569.3cbc548f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4807],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),i=a(89466);function y(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??y(a);return function(e){const t=(0,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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(!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}),[y,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=s??y;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:y}=(0,o.a_)(),c=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(y(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":c(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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:c},o,{className:(0,p.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},76945:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>y});var n=a(58168),r=(a(96540),a(15680)),p=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],c={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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([[4807],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(p.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>v});var n=a(58168),r=a(96540),p=a(20053),o=a(23104),l=a(56347),s=a(57485),u=a(31682),i=a(89466);function y(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??y(a);return function(e){const t=(0,u.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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=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(!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}),[y,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,p]=(0,i.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&p.set(e)}),[a,p])]}({groupId:n}),g=(()=>{const e=s??y;return d({value:e,tabValues:p})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const i=[],{blockElementScrollPositionUntilNextRender:y}=(0,o.a_)(),c=e=>{const t=e.currentTarget,a=i.indexOf(t),n=u[a].value;n!==l&&(y(t),s(n))},d=e=>{let t=null;switch(e.key){case"Enter":c(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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>i.push(e),onKeyDown:d,onClick:c},o,{className:(0,p.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===t})}),a??t)})))}function T(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 N(e){const t=h(e);return r.createElement("div",{className:(0,p.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(T,(0,n.A)({},e,t)))}function v(e){const t=(0,g.A)();return r.createElement(N,(0,n.A)({key:String(t)},e))}},76945:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>y});var n=a(58168),r=(a(96540),a(15680)),p=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],c={toc:y},d="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(d,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In some special cases, you want to override the GraphQL return type that is attributed by default by GraphQLite."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, GraphQLite will generate a GraphQL schema with a field ",(0,r.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,r.yg)("inlineCode",{parentName:"p"},"string"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"type Product {\n id: String!\n}\n")),(0,r.yg)("p",null,"GraphQL comes with an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," scalar type. But PHP has no such type. So GraphQLite does not know when a variable\nis an ",(0,r.yg)("inlineCode",{parentName:"p"},"ID")," or not."),(0,r.yg)("p",null,"You can help GraphQLite by manually specifying the output type to use:"),(0,r.yg)(p.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' #[Field(outputType: "ID")]\n'))),(0,r.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},' /**\n * @Field(name="id", outputType="ID")\n */\n')))),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute will map the return value of the method to the output type passed in parameter."),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"outputType")," attribute in the following annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField"))),(0,r.yg)("h2",{id:"registering-a-custom-output-type-advanced"},"Registering a custom output type (advanced)"),(0,r.yg)("p",null,"In order to create a custom output type, you need to:"),(0,r.yg)("ol",null,(0,r.yg)("li",{parentName:"ol"},"Design a class that extends ",(0,r.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ObjectType"),"."),(0,r.yg)("li",{parentName:"ol"},"Register this class in the GraphQL schema.")),(0,r.yg)("p",null,"You'll find more details on the ",(0,r.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/type-definitions/object-types/"},"Webonyx documentation"),"."),(0,r.yg)("hr",null),(0,r.yg)("p",null,"In order to find existing types, the schema is using ",(0,r.yg)("em",{parentName:"p"},"type mappers")," (classes implementing the ",(0,r.yg)("inlineCode",{parentName:"p"},"TypeMapperInterface")," interface)."),(0,r.yg)("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.yg)("h3",{id:"symfony-users"},"Symfony users"),(0,r.yg)("p",null,"Any class extending ",(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"graphql.output_type")," tag:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h3",{id:"other-frameworks"},"Other frameworks"),(0,r.yg)("p",null,"The easiest way is to use a ",(0,r.yg)("inlineCode",{parentName:"p"},"StaticTypeMapper"),". Use this class to register custom output types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-custom-scalar-type-advanced"},"Registering a custom scalar type (advanced)"),(0,r.yg)("p",null,"If you need to add custom scalar types, first, check the ",(0,r.yg)("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.yg)("p",null,"You still need to develop your custom scalar type? Ok, let's get started."),(0,r.yg)("p",null,"In order to add a scalar type in GraphQLite, you need to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"create a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"GraphQL\\Type\\Definition\\ScalarType"),"."),(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"RootTypeMapperInterface"),"."),(0,r.yg)("li",{parentName:"ul"},'create a "type mapper factory" that will be in charge of creating your "type mapper".')),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"null")," if there no match."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"mapNameToType")," should return your GraphQL scalar type if ",(0,r.yg)("inlineCode",{parentName:"p"},"$typeName")," is the name of your scalar type."),(0,r.yg)("p",null,"RootTypeMapper are organized ",(0,r.yg)("strong",{parentName:"p"},"in a chain")," (they are actually middlewares).\nEach instance of a ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapper")," holds a reference on the next root type mapper to be called in the chain."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, in order to create an instance of your ",(0,r.yg)("inlineCode",{parentName:"p"},"AnyScalarTypeMapper")," class, you need an instance of the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper in the chain.\nHow do you get the ",(0,r.yg)("inlineCode",{parentName:"p"},"$next")," type mapper? Through a factory:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, you need to register this factory in your application, and we are done."),(0,r.yg)("p",null,"You can register your own root mapper factories using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addRootTypeMapperFactory()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addRootTypeMapperFactory(new AnyScalarTypeMapperFactory());\n")),(0,r.yg)("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.54104957.js b/assets/js/d49884c9.270e6dca.js similarity index 99% rename from assets/js/d49884c9.54104957.js rename to assets/js/d49884c9.270e6dca.js index 6d1abef7e..57037c8e2 100644 --- a/assets/js/d49884c9.54104957.js +++ b/assets/js/d49884c9.270e6dca.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3712],{32670:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>o,contentTitle:()=>l,default:()=>h,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var n=a(58168),r=(a(96540),a(15680));a(67443);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},l=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},o={},p=[{value:"Simple query",id:"simple-query",level:2},{value:"About attributes",id:"about-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}],u={toc:p},y="wrapper";function h(e){let{components:t,...i}=e;return(0,r.yg)(y,(0,n.A)({},u,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]")," attribute. For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-attributes"},"About attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on attributes."),(0,r.yg)("p",null,"It supports the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),'), the "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),") was dropped."),(0,r.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:a(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute is used to define the GraphQL fields. This attribute must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL attributes are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," attributes and for most project, this is the fastest and easiest route."),(0,r.yg)("p",null,"If you feel that GraphQL attributes 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.")))}h.isMDXComponent=!0},67258:(e,t,a)=>{a.d(t,{A:()=>n});const n=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3712],{32670:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>o,contentTitle:()=>l,default:()=>h,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var n=a(58168),r=(a(96540),a(15680));a(67443);const i={id:"queries",title:"Queries",sidebar_label:"Queries"},l=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},o={},p=[{value:"Simple query",id:"simple-query",level:2},{value:"About attributes",id:"about-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}],u={toc:p},y="wrapper";function h(e){let{components:t,...i}=e;return(0,r.yg)(y,(0,n.A)({},u,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]")," attribute. For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"about-attributes"},"About attributes"),(0,r.yg)("p",null,"GraphQLite relies a lot on attributes."),(0,r.yg)("p",null,"It supports the new PHP 8 attributes (",(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),'), the "Doctrine annotations" style (',(0,r.yg)("inlineCode",{parentName:"p"},"#[Query]"),") was dropped."),(0,r.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:a(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute is used to define the GraphQL fields. This attribute must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL attributes are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," attributes and for most project, this is the fastest and easiest route."),(0,r.yg)("p",null,"If you feel that GraphQL attributes 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.")))}h.isMDXComponent=!0},67258:(e,t,a)=>{a.d(t,{A:()=>n});const n=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/d4c8693b.f893e966.js b/assets/js/d4c8693b.5cb693a0.js similarity index 99% rename from assets/js/d4c8693b.f893e966.js rename to assets/js/d4c8693b.5cb693a0.js index 02c7c3040..9c988443b 100644 --- a/assets/js/d4c8693b.f893e966.js +++ b/assets/js/d4c8693b.5cb693a0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9282],{68445:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/4.1/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.1/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9282],{68445:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/4.1/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/4.1/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d589d3a7.89953d13.js b/assets/js/d589d3a7.0f1cba51.js similarity index 97% rename from assets/js/d589d3a7.89953d13.js rename to assets/js/d589d3a7.0f1cba51.js index 27bfa81fa..55b63645f 100644 --- a/assets/js/d589d3a7.89953d13.js +++ b/assets/js/d589d3a7.0f1cba51.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7924],{54902:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>i,metadata:()=>s,toc:()=>l});var r=a(58168),n=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:l},g="wrapper";function p(t){let{components:e,...a}=t;return(0,n.yg)(g,(0,r.A)({},c,a,{components:e,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("a",{parentName:"li",href:"/docs/next/symfony-bundle"},"Get started with Symfony")),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("a",{parentName:"li",href:"/docs/next/laravel-package"},"Get started with Laravel")),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("a",{parentName:"li",href:"/docs/next/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("a",{parentName:"li",href:"/docs/next/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7924],{54902:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>i,metadata:()=>s,toc:()=>l});var r=a(58168),n=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:l},g="wrapper";function p(t){let{components:e,...a}=t;return(0,n.yg)(g,(0,r.A)({},c,a,{components:e,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("a",{parentName:"li",href:"/docs/next/symfony-bundle"},"Get started with Symfony")),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("a",{parentName:"li",href:"/docs/next/laravel-package"},"Get started with Laravel")),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("a",{parentName:"li",href:"/docs/next/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("a",{parentName:"li",href:"/docs/next/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d6188fd4.d65a31dd.js b/assets/js/d6188fd4.b2e76004.js similarity index 98% rename from assets/js/d6188fd4.d65a31dd.js rename to assets/js/d6188fd4.b2e76004.js index f20fc1a66..8147ad574 100644 --- a/assets/js/d6188fd4.d65a31dd.js +++ b/assets/js/d6188fd4.b2e76004.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9828],{59085:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.1/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/6.1/query-plan"}},c={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.yg)(p,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.1/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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([[9828],{59085:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var i=n(58168),r=(n(96540),n(15680));n(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.1/fine-grained-security"},next:{title:"Query plan",permalink:"/docs/6.1/query-plan"}},c={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...n}=e;return(0,r.yg)(p,(0,i.A)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.1/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("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/d62b7e4c.8ec984fe.js b/assets/js/d62b7e4c.41f33cbc.js similarity index 99% rename from assets/js/d62b7e4c.8ec984fe.js rename to assets/js/d62b7e4c.41f33cbc.js index 3eb940658..45ba0e708 100644 --- a/assets/js/d62b7e4c.8ec984fe.js +++ b/assets/js/d62b7e4c.41f33cbc.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8330],{71843:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var a=n(58168),i=(n(96540),n(15680));n(67443);const o={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},r=void 0,l={unversionedId:"external-type-declaration",id:"version-8.0.0/external-type-declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an attribute on a domain class.",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/external-type-declaration.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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] attribute with the class attribute",id:"type-attribute-with-the-class-attribute",level:2},{value:"#[SourceField] attribute",id:"sourcefield-attribute",level:2},{value:"#[MagicField] attribute",id:"magicfield-attribute",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without attributes)",id:"declaring-fields-dynamically-without-attributes",level:2}],d={toc:u},p="wrapper";function c(e){let{components:t,...n}=e;return(0,i.yg)(p,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In some cases, you cannot or do not want to put an attribute on a domain class."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,i.yg)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with attributes from the view layer"),(0,i.yg)("li",{parentName:"ul"},"etc.")),(0,i.yg)("h2",{id:"type-attribute-with-the-class-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"#[Type]")," attribute with the ",(0,i.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,i.yg)("p",null,"GraphQLite allows you to use a ",(0,i.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute with the ",(0,i.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,i.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("p",null,"In methods with a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute, the first parameter is the ",(0,i.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,i.yg)("h2",{id:"sourcefield-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"#[SourceField]")," attribute"),(0,i.yg)("p",null,"If you don't want to rewrite all ",(0,i.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,i.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,i.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,i.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,i.yg)("h2",{id:"magicfield-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"#[MagicField]")," attribute"),(0,i.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,i.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[MagicField]")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,i.yg)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,i.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,i.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,i.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,i.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" argument.'),(0,i.yg)("pre",null,(0,i.yg)("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#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price", annotations: [new Logged(), new Right("CAN_ACCESS_Price"), new FailWith(null)])]\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,i.yg)("p",null,"Any attributes described in the ",(0,i.yg)("a",{parentName:"p",href:"/docs/authentication-authorization"},"Authentication and authorization page"),", or any attribute this is actually a ",(0,i.yg)("a",{parentName:"p",href:"/docs/field-middlewares"},'"field middleware"')," can be used in the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]"),' "annotations" argument.'),(0,i.yg)("h2",{id:"declaring-fields-dynamically-without-attributes"},"Declaring fields dynamically (without attributes)"),(0,i.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," attributes at development time.\nIf you need to decide the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," at runtime, you can implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,i.yg)("pre",null,(0,i.yg)("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', 'annotations'=>[new Logged()]]),\n ];\n } else {\n return [];\n }\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8330],{71843:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>l,toc:()=>u});var a=n(58168),i=(n(96540),n(15680));n(67443);const o={id:"external-type-declaration",title:"External type declaration",sidebar_label:"External type declaration"},r=void 0,l={unversionedId:"external-type-declaration",id:"version-8.0.0/external-type-declaration",title:"External type declaration",description:"In some cases, you cannot or do not want to put an attribute on a domain class.",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/external-type-declaration.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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] attribute with the class attribute",id:"type-attribute-with-the-class-attribute",level:2},{value:"#[SourceField] attribute",id:"sourcefield-attribute",level:2},{value:"#[MagicField] attribute",id:"magicfield-attribute",level:2},{value:"Authentication and authorization",id:"authentication-and-authorization",level:3},{value:"Declaring fields dynamically (without attributes)",id:"declaring-fields-dynamically-without-attributes",level:2}],d={toc:u},p="wrapper";function c(e){let{components:t,...n}=e;return(0,i.yg)(p,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In some cases, you cannot or do not want to put an attribute on a domain class."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,i.yg)("li",{parentName:"ul"},"You are doing domain-driven design and don't want to clutter your domain object with attributes from the view layer"),(0,i.yg)("li",{parentName:"ul"},"etc.")),(0,i.yg)("h2",{id:"type-attribute-with-the-class-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"#[Type]")," attribute with the ",(0,i.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,i.yg)("p",null,"GraphQLite allows you to use a ",(0,i.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Type]")," attribute with the ",(0,i.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,i.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("p",null,"In methods with a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute, the first parameter is the ",(0,i.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,i.yg)("h2",{id:"sourcefield-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"#[SourceField]")," attribute"),(0,i.yg)("p",null,"If you don't want to rewrite all ",(0,i.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,i.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,i.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"isName()"),").\nYou can set different name to look for with ",(0,i.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,i.yg)("h2",{id:"magicfield-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"#[MagicField]")," attribute"),(0,i.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,i.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[MagicField]")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,i.yg)("inlineCode",{parentName:"p"},"Product")," object.\nYou can set different name to look for with ",(0,i.yg)("inlineCode",{parentName:"p"},"sourceName")," attribute."),(0,i.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,i.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,i.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" argument.'),(0,i.yg)("pre",null,(0,i.yg)("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#[Type(class: Product::class)]\n#[SourceField(name: "name")]\n#[SourceField(name: "price", annotations: [new Logged(), new Right("CAN_ACCESS_Price"), new FailWith(null)])]\nclass ProductType extends AbstractAnnotatedObjectType\n{\n}\n')),(0,i.yg)("p",null,"Any attributes described in the ",(0,i.yg)("a",{parentName:"p",href:"/docs/authentication-authorization"},"Authentication and authorization page"),", or any attribute this is actually a ",(0,i.yg)("a",{parentName:"p",href:"/docs/field-middlewares"},'"field middleware"')," can be used in the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]"),' "annotations" argument.'),(0,i.yg)("h2",{id:"declaring-fields-dynamically-without-attributes"},"Declaring fields dynamically (without attributes)"),(0,i.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," attributes at development time.\nIf you need to decide the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"#[SourceField]")," at runtime, you can implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,i.yg)("pre",null,(0,i.yg)("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', 'annotations'=>[new Logged()]]),\n ];\n } else {\n return [];\n }\n }\n}\n")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d6b4b60c.076729ae.js b/assets/js/d6b4b60c.18c79ff2.js similarity index 99% rename from assets/js/d6b4b60c.076729ae.js rename to assets/js/d6b4b60c.18c79ff2.js index f8750e68d..33d3b3c74 100644 --- a/assets/js/d6b4b60c.076729ae.js +++ b/assets/js/d6b4b60c.18c79ff2.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6556],{48204:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var n=a(58168),l=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},g={},p=[{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}],y={toc:p},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("a",{parentName:"td",href:"/docs/4.0/external_type_declaration"},"the class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("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.yg)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/4.0/extend_type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.0/type_mapping"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.0/type_mapping"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.0/type_mapping"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.0/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("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.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.0/extend_input_type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.0/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.0/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.0/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.0/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6556],{48204:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>g,contentTitle:()=>i,default:()=>m,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var n=a(58168),l=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},g={},p=[{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}],y={toc:p},d="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(d,(0,n.A)({},y,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("h2",{id:"query-annotation"},"@Query annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query")," annotation is used to declare a GraphQL query."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the query. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"mutation-annotation"},"@Mutation annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," annotation is used to declare a GraphQL mutation."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": controller methods."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the mutation. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.0/custom-types"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"type-annotation"},"@Type annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to declare a GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("a",{parentName:"td",href:"/docs/4.0/external_type_declaration"},"the class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@Type")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Defaults to ",(0,l.yg)("em",{parentName:"td"},"true"),". Whether the targeted PHP class should be mapped by default to this type.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"external"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"Whether this is an ",(0,l.yg)("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.yg)("h2",{id:"extendtype-annotation"},"@ExtendType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation is used to add fields to an existing GraphQL object type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"class"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted class. ",(0,l.yg)("a",{parentName:"td",href:"/docs/4.0/extend_type"},"The class annotated with ",(0,l.yg)("inlineCode",{parentName:"a"},"@ExtendType")," is a service"),".")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},"see below"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The targeted GraphQL output type.")))),(0,l.yg)("p",null,'One and only one of "class" and "name" parameter can be passed at the same time.'),(0,l.yg)("h2",{id:"field-annotation"},"@Field annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods of classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field. If skipped, the name of the method is used instead.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.0/type_mapping"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of a query.")))),(0,l.yg)("h2",{id:"sourcefield-annotation"},"@SourceField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation is used to declare a GraphQL field."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.0/type_mapping"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Forces the GraphQL output type of the field. Otherwise, return type is used.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive."),(0,l.yg)("h2",{id:"magicfield-annotation"},"@MagicField annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation is used to declare a GraphQL field that originates from a PHP magic property (using ",(0,l.yg)("inlineCode",{parentName:"p"},"__get")," magic method)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("a",{parentName:"td",href:"/docs/4.0/type_mapping"},"outputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL output type of the field.")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"phpType"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no"),"(*)"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The PHP type of the field (as you would write it in a Docblock)")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"annotations"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"array\\"),(0,l.yg)("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.yg)("p",null,"(*) ",(0,l.yg)("strong",{parentName:"p"},"Note"),": ",(0,l.yg)("inlineCode",{parentName:"p"},"outputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"phpType")," are mutually exclusive. You MUST provide one of them."),(0,l.yg)("h2",{id:"logged-annotation"},"@Logged annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," annotation is used to declare a Query/Mutation/Field is only visible to logged users."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("p",null,"This annotation allows no attributes."),(0,l.yg)("h2",{id:"right-annotation"},"@Right annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotation is used to declare a Query/Mutation/Field is only visible to users with a specific right."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the right.")))),(0,l.yg)("h2",{id:"failwith-annotation"},"@FailWith annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"mixed"),(0,l.yg)("td",{parentName:"tr",align:null},"The value to return if the user is not authorized.")))),(0,l.yg)("h2",{id:"hideifunauthorized-annotation"},"@HideIfUnauthorized annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations)."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," and one of ",(0,l.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Right")," annotations."),(0,l.yg)("p",null,(0,l.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@FailWith")," are mutually exclusive."),(0,l.yg)("h2",{id:"injectuser-annotation"},"@InjectUser annotation"),(0,l.yg)("p",null,"Use the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")))),(0,l.yg)("h2",{id:"security-annotation"},"@Security annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("p",null,"See ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.0/fine-grained-security"},"the fine grained security page")," for more details."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"default")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The security expression")))),(0,l.yg)("h2",{id:"factory-annotation"},"@Factory annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation is used to declare a factory that turns GraphQL input types into objects."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"default"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"bool"),(0,l.yg)("td",{parentName:"tr",align:null},"If ",(0,l.yg)("inlineCode",{parentName:"td"},"true"),", this factory will be used by default for its PHP return type. If set to ",(0,l.yg)("inlineCode",{parentName:"td"},"false"),", you must explicitly ",(0,l.yg)("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.yg)("inlineCode",{parentName:"a"},"@Parameter")," annotation"),".")))),(0,l.yg)("h2",{id:"useinputtype-annotation"},"@UseInputType annotation"),(0,l.yg)("p",null,"Used to override the GraphQL input type of a PHP parameter."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"inputType")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type to force for this input field")))),(0,l.yg)("h2",{id:"decorate-annotation"},"@Decorate annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation is used ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.0/extend_input_type"},"to extend/modify/decorate an input type declared with the ",(0,l.yg)("inlineCode",{parentName:"a"},"@Factory")," annotation"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),': methods from classes in the "types" namespace.'),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The GraphQL input type name extended by this decorator.")))),(0,l.yg)("h2",{id:"autowire-annotation"},"@Autowire annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.0/autowiring"},"Resolves a PHP parameter from the container"),"."),(0,l.yg)("p",null,"Useful to inject services directly into ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," method arguments."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"identifier")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("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.yg)("h2",{id:"hideparameter-annotation"},"@HideParameter annotation"),(0,l.yg)("p",null,"Removes ",(0,l.yg)("a",{parentName:"p",href:"/docs/4.0/input-types#ignoring-some-parameters"},"an argument from the GraphQL schema"),"."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter to hide")))),(0,l.yg)("h2",{id:"validate-annotation"},"@Validate annotation"),(0,l.yg)("div",{class:"alert alert--info"},"This annotation is only available in the GraphQLite Laravel package"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.0/laravel-package-advanced"},"Validates a user input in Laravel"),"."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"rule")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"Laravel validation rules")))),(0,l.yg)("p",null,"Sample:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre"},'@Validate(for="$email", rule="email|unique:users")\n')),(0,l.yg)("h2",{id:"assertion-annotation"},"@Assertion annotation"),(0,l.yg)("p",null,(0,l.yg)("a",{parentName:"p",href:"/docs/4.0/validation"},"Validates a user input"),"."),(0,l.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"@Assertion")," annotation is available in the ",(0,l.yg)("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.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": methods annotated with ",(0,l.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Mutation"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Field"),", ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," or ",(0,l.yg)("inlineCode",{parentName:"p"},"@Decorator")," annotation."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"for")),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"yes")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the PHP parameter")),(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"constraint")),(0,l.yg)("td",{parentName:"tr",align:null},"*yes"),(0,l.yg)("td",{parentName:"tr",align:null},"annotation"),(0,l.yg)("td",{parentName:"tr",align:null},"One (or many) Symfony validation annotations.")))),(0,l.yg)("h2",{id:"enumtype-annotation"},"@EnumType annotation"),(0,l.yg)("p",null,"The ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum"),"\nis automatically mapped to a GraphQL enum type."),(0,l.yg)("p",null,(0,l.yg)("strong",{parentName:"p"},"Applies on"),": classes extending the ",(0,l.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," base class."),(0,l.yg)("table",null,(0,l.yg)("thead",{parentName:"table"},(0,l.yg)("tr",{parentName:"thead"},(0,l.yg)("th",{parentName:"tr",align:null},"Attribute"),(0,l.yg)("th",{parentName:"tr",align:null},"Compulsory"),(0,l.yg)("th",{parentName:"tr",align:null},"Type"),(0,l.yg)("th",{parentName:"tr",align:null},"Definition"))),(0,l.yg)("tbody",{parentName:"table"},(0,l.yg)("tr",{parentName:"tbody"},(0,l.yg)("td",{parentName:"tr",align:null},"name"),(0,l.yg)("td",{parentName:"tr",align:null},(0,l.yg)("em",{parentName:"td"},"no")),(0,l.yg)("td",{parentName:"tr",align:null},"string"),(0,l.yg)("td",{parentName:"tr",align:null},"The name of the enum type (in the GraphQL schema)")))))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d7067606.e1cf7b88.js b/assets/js/d7067606.25f18bdb.js similarity index 99% rename from assets/js/d7067606.e1cf7b88.js rename to assets/js/d7067606.25f18bdb.js index cd70c72a1..9f0189812 100644 --- a/assets/js/d7067606.e1cf7b88.js +++ b/assets/js/d7067606.25f18bdb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6579],{19365:(e,a,t)=>{t.d(a,{A:()=>l});var n=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function l(e){let{children:a,hidden:t,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,l),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>N});var n=t(58168),r=t(96540),i=t(20053),l=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function d(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function g(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:t}=e;const n=(0,o.W6)(),i=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const a=new URLSearchParams(n.location.search);a.set(i,e),n.replace({...n.location,search:a.toString()})}),[i,n])]}function m(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=d(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:i}))),[s,u]=h({queryString:t,groupId:n}),[c,m]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,i]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:n}),y=(()=>{const e=s??c;return g({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,i]),tabValues:i}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.a_)(),d=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==o&&(c(a),s(n))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:l}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},l,{className:(0,i.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":o===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,a)),r.createElement(b,(0,n.A)({},e,a)))}function N(e){const a=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},67016:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>s,contentTitle:()=>l,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>u});var n=t(58168),r=(t(96540),t(15680));t(67443),t(11470),t(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.1/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/6.1/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:a,...t}=e;return(0,r.yg)(c,(0,n.A)({},p,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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([[6579],{19365:(e,a,t)=>{t.d(a,{A:()=>l});var n=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function l(e){let{children:a,hidden:t,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,l),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>N});var n=t(58168),r=t(96540),i=t(20053),l=t(23104),o=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function d(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function g(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:t}=e;const n=(0,o.W6)(),i=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const a=new URLSearchParams(n.location.search);a.set(i,e),n.replace({...n.location,search:a.toString()})}),[i,n])]}function m(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=d(e),[l,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:i}))),[s,u]=h({queryString:t,groupId:n}),[c,m]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,i]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:n}),y=(()=>{const e=s??c;return g({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,i]),tabValues:i}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:t,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.a_)(),d=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==o&&(c(a),s(n))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:l}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},l,{className:(0,i.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":o===a})}),t??a)})))}function b(e){let{lazy:a,children:t,selectedValue:n}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(v,(0,n.A)({},e,a)),r.createElement(b,(0,n.A)({},e,a)))}function N(e){const a=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},67016:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>s,contentTitle:()=>l,default:()=>d,frontMatter:()=>i,metadata:()=>o,toc:()=>u});var n=t(58168),r=(t(96540),t(15680));t(67443),t(11470),t(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.1/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/6.1/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:a,...t}=e;return(0,r.yg)(c,(0,n.A)({},p,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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.2fee95fb.js b/assets/js/d8037f4c.c3b97d24.js similarity index 97% rename from assets/js/d8037f4c.2fee95fb.js rename to assets/js/d8037f4c.c3b97d24.js index dffa1a650..317a26162 100644 --- a/assets/js/d8037f4c.2fee95fb.js +++ b/assets/js/d8037f4c.c3b97d24.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4548],{35924:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4548],{35924:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>i,metadata:()=>a,toc:()=>u});var n=o(58168),r=(o(96540),o(15680));o(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],c={toc:u},p="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(p,(0,n.A)({},c,o,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},'Cannot autowire service "',(0,r.yg)("em",{parentName:"strong"},"[some input type]"),'": argument "$..." of method "..." is type-hinted "...", you should configure its value explicitly.')),(0,r.yg)("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.yg)("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.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"config/graphqlite.yml")," file to point to your new namespace."))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d8ff000f.410fde9c.js b/assets/js/d8ff000f.23ad97e0.js similarity index 99% rename from assets/js/d8ff000f.410fde9c.js rename to assets/js/d8ff000f.23ad97e0.js index 17efd8221..a86d188b1 100644 --- a/assets/js/d8ff000f.410fde9c.js +++ b/assets/js/d8ff000f.23ad97e0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1661],{64673:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>l});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:"Attributes reference",permalink:"/docs/next/annotations-reference"}},u={},l=[{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:l},p="wrapper";function d(t){let{components:e,...n}=t;return(0,i.yg)(p,(0,a.A)({},c,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.yg)("div",{class:"alert alert--danger"},(0,i.yg)("strong",null,"Unsupported!")," Doctrine annotations are replaced in favor of native PHP 8 attributes."),(0,i.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.yg)("p",null,"The same code can be written this way:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.yg)("p",null,"They support the same attributes too."),(0,i.yg)("p",null,"A few notable differences:"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("p",null,"Let's take an example with the ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/autowiring"},(0,i.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")),(0,i.yg)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,i.yg)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/rectorphp/rector"},"Rector library"),". To do so, you'll want to use the following rector configuration:"),(0,i.yg)("pre",null,(0,i.yg)("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([[1661],{64673:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>u,contentTitle:()=>r,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>l});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:"Attributes reference",permalink:"/docs/next/annotations-reference"}},u={},l=[{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:l},p="wrapper";function d(t){let{components:e,...n}=t;return(0,i.yg)(p,(0,a.A)({},c,n,{components:e,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,i.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,i.yg)("div",{class:"alert alert--danger"},(0,i.yg)("strong",null,"Unsupported!")," Doctrine annotations are replaced in favor of native PHP 8 attributes."),(0,i.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,i.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,i.yg)("p",null,"The same code can be written this way:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,i.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,i.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,i.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,i.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,i.yg)("p",null,"They support the same attributes too."),(0,i.yg)("p",null,"A few notable differences:"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("p",null,"Let's take an example with the ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/autowiring"},(0,i.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")),(0,i.yg)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,i.yg)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,i.yg)("a",{parentName:"p",href:"https://github.com/rectorphp/rector"},"Rector library"),". To do so, you'll want to use the following rector configuration:"),(0,i.yg)("pre",null,(0,i.yg)("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/d9523c62.557f0440.js b/assets/js/d9523c62.a8413bae.js similarity index 99% rename from assets/js/d9523c62.557f0440.js rename to assets/js/d9523c62.a8413bae.js index bc1f56e81..8584807de 100644 --- a/assets/js/d9523c62.557f0440.js +++ b/assets/js/d9523c62.a8413bae.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1465],{39537:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:n,...t}=e;return(0,i.yg)(c,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,i.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,i.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,i.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,i.yg)("p",null,"GraphQLite allows you to use a ",(0,i.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,i.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,i.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("p",null,"In methods with a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,i.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,i.yg)("h2",{id:"sourcefield-annotation"},(0,i.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,i.yg)("p",null,"If you don't want to rewrite all ",(0,i.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,i.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,i.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"isName()"),")."),(0,i.yg)("h2",{id:"magicfield-annotation"},(0,i.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,i.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,i.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,i.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,i.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,i.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Any annotations described in the ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/authentication_authorization"},"Authentication and authorization page")," can be used in the ",(0,i.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,i.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,i.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,i.yg)("pre",null,(0,i.yg)("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([[1465],{39537:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:n,...t}=e;return(0,i.yg)(c,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"In some cases, you cannot or do not want to put an annotation on a domain class."),(0,i.yg)("p",null,"For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The class you want to annotate is part of a third party library and you cannot modify it"),(0,i.yg)("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.yg)("li",{parentName:"ul"},"etc.")),(0,i.yg)("h2",{id:"type-annotation-with-the-class-attribute"},(0,i.yg)("inlineCode",{parentName:"h2"},"@Type")," annotation with the ",(0,i.yg)("inlineCode",{parentName:"h2"},"class")," attribute"),(0,i.yg)("p",null,"GraphQLite allows you to use a ",(0,i.yg)("em",{parentName:"p"},"proxy")," class thanks to the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Type")," annotation with the ",(0,i.yg)("inlineCode",{parentName:"p"},"class")," attribute:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class must be in the ",(0,i.yg)("em",{parentName:"p"},"types")," namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"p"},"service"),". You can therefore inject dependencies in it."),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("p",null,"In methods with a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, the first parameter is the ",(0,i.yg)("em",{parentName:"p"},"resolved object")," we are working on. Any additional parameters are used as arguments."),(0,i.yg)("h2",{id:"sourcefield-annotation"},(0,i.yg)("inlineCode",{parentName:"h2"},"@SourceField")," annotation"),(0,i.yg)("p",null,"If you don't want to rewrite all ",(0,i.yg)("em",{parentName:"p"},"getters")," of your base class, you may use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotation:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"By doing so, you let GraphQLite know that the type exposes the ",(0,i.yg)("inlineCode",{parentName:"p"},"getName")," method of the underlying ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.yg)("p",null,"Internally, GraphQLite will look for methods named ",(0,i.yg)("inlineCode",{parentName:"p"},"name()"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"isName()"),")."),(0,i.yg)("h2",{id:"magicfield-annotation"},(0,i.yg)("inlineCode",{parentName:"h2"},"@MagicField")," annotation"),(0,i.yg)("p",null,"If your object has no getters, but instead uses magic properties (using the magic ",(0,i.yg)("inlineCode",{parentName:"p"},"__get")," method), you should use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,'By doing so, you let GraphQLite know that the type exposes "name" and the "price" magic properties of the underlying ',(0,i.yg)("inlineCode",{parentName:"p"},"Product")," object."),(0,i.yg)("p",null,"This is particularly useful in frameworks like Laravel, where Eloquent is making a very wide use of such properties."),(0,i.yg)("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.yg)("h3",{id:"authentication-and-authorization"},"Authentication and authorization"),(0,i.yg)("p",null,'You may also check for logged users or users with a specific right using the "annotations" property.'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Any annotations described in the ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/authentication_authorization"},"Authentication and authorization page")," can be used in the ",(0,i.yg)("inlineCode",{parentName:"p"},"@SourceField"),' "annotations" attribute.'),(0,i.yg)("h2",{id:"declaring-fields-dynamically-without-annotations"},"Declaring fields dynamically (without annotations)"),(0,i.yg)("p",null,"In some very particular cases, you might not know exactly the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"@SourceField")," annotations at development time.\nIf you need to decide the list of ",(0,i.yg)("inlineCode",{parentName:"p"},"@SourceField")," at runtime, you can implement the ",(0,i.yg)("inlineCode",{parentName:"p"},"FromSourceFieldsInterface"),":"),(0,i.yg)("pre",null,(0,i.yg)("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.ea705c74.js b/assets/js/db6a6f31.15ffc30c.js similarity index 99% rename from assets/js/db6a6f31.ea705c74.js rename to assets/js/db6a6f31.15ffc30c.js index 259d245db..7bfa61b21 100644 --- a/assets/js/db6a6f31.ea705c74.js +++ b/assets/js/db6a6f31.15ffc30c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2958],{98872:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>r,default:()=>p,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function p(e){let{components:n,...t}=e;return(0,i.yg)(g,(0,a.A)({},u,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"If the ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/authentication_authorization#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.yg)("p",null,"Using the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,i.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,i.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,i.yg)("li",{parentName:"ul"},"...")),(0,i.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,i.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,i.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,i.yg)("code",null,"@Security")," annotation and Symfony's ",(0,i.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,i.yg)("h2",{id:"the-is_granted-function"},"The ",(0,i.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")),(0,i.yg)("p",null,"is similar to"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')),(0,i.yg)("p",null,"In addition, the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, the ",(0,i.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,i.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,i.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,i.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/authentication_authorization#not-throwing-errors"},(0,i.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.yg)("p",null,"You cannot use the ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,i.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,i.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")),(0,i.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,i.yg)("p",null,"If you are using Laravel, you will ",(0,i.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,i.yg)("p",null,"If you are using another framework, you need to know that the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,i.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2958],{98872:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>r,default:()=>p,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function p(e){let{components:n,...t}=e;return(0,i.yg)(g,(0,a.A)({},u,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"If the ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/authentication_authorization#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.yg)("p",null,"Using the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,i.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,i.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,i.yg)("li",{parentName:"ul"},"...")),(0,i.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,i.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,i.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,i.yg)("code",null,"@Security")," annotation and Symfony's ",(0,i.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,i.yg)("h2",{id:"the-is_granted-function"},"The ",(0,i.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")),(0,i.yg)("p",null,"is similar to"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')),(0,i.yg)("p",null,"In addition, the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, the ",(0,i.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,i.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,i.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,i.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/authentication_authorization#not-throwing-errors"},(0,i.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.yg)("p",null,"You cannot use the ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,i.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,i.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")),(0,i.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,i.yg)("p",null,"If you are using Laravel, you will ",(0,i.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,i.yg)("p",null,"If you are using another framework, you need to know that the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,i.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,i.yg)("a",{parentName:"p",href:"/docs/4.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/dbf2bcb3.e7a2a4f7.js b/assets/js/dbf2bcb3.c7a36617.js similarity index 99% rename from assets/js/dbf2bcb3.e7a2a4f7.js rename to assets/js/dbf2bcb3.c7a36617.js index 8fac072a0..f2c5942ac 100644 --- a/assets/js/dbf2bcb3.e7a2a4f7.js +++ b/assets/js/dbf2bcb3.c7a36617.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8025],{15495:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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/6.1/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/migrating.md",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"docs",previous:{title:"Troubleshooting",permalink:"/docs/6.1/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/6.1/doctrine-annotations-attributes"}},s={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/6.1/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/6.1/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8025],{15495:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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/6.1/migrating",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/migrating.md",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"migrating",title:"Migrating",sidebar_label:"Migrating"},sidebar:"docs",previous:{title:"Troubleshooting",permalink:"/docs/6.1/troubleshooting"},next:{title:"Annotations VS Attributes",permalink:"/docs/6.1/doctrine-annotations-attributes"}},s={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/6.1/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/6.1/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/dc9a99e0.fb28ae35.js b/assets/js/dc9a99e0.c8144eaf.js similarity index 99% rename from assets/js/dc9a99e0.fb28ae35.js rename to assets/js/dc9a99e0.c8144eaf.js index ea781cbd3..a304aa0c0 100644 --- a/assets/js/dc9a99e0.fb28ae35.js +++ b/assets/js/dc9a99e0.c8144eaf.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2187],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),l=a(20053);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.A)(u.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>P});var n=a(58168),l=a(96540),u=a(20053),r=a(23104),i=a(56347),o=a(57485),p=a(31682),s=a(89466);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:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function d(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,p.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=d(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(!y({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]=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,u]=(0,s.Dv)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),g=(()=>{const e=o??c;return y({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),h(e)}),[p,h,u]),tabValues:u}}var g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),d=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(c(t),o(n))},y=e=>{let t=null;switch(e.key){case"Enter":d(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.A)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.A)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},r,{className:(0,u.A)("tabs__item",f.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 T(e){const t=h(e);return l.createElement("div",{className:(0,u.A)("tabs-container",f.tabList)},l.createElement(b,(0,n.A)({},e,t)),l.createElement(v,(0,n.A)({},e,t)))}function P(e){const t=(0,g.A)();return l.createElement(T,(0,n.A)({key:String(t)},e))}},23255:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>m,frontMatter:()=>i,metadata:()=>p,toc:()=>c});var n=a(58168),l=(a(96540),a(15680)),u=(a(67443),a(11470)),r=a(19365);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-7.0.0/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-7.0.0/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/7.0.0/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/multiple-output-types.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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/7.0.0/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/7.0.0/symfony-bundle-advanced"}},s={},c=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:c},y="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/external-type-declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("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.yg)("p",null,"So instead of writing:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.yg)("p",null,"you will write:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2187],{19365:(e,t,a)=>{a.d(t,{A:()=>r});var n=a(96540),l=a(20053);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.A)(u.tabItem,r),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>P});var n=a(58168),l=a(96540),u=a(20053),r=a(23104),i=a(56347),o=a(57485),p=a(31682),s=a(89466);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:a,attributes:n,default:l}}=e;return{value:t,label:a,attributes:n,default:l}}))}function d(e){const{values:t,children:a}=e;return(0,l.useMemo)((()=>{const e=t??c(a);return function(e){const t=(0,p.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 h(e){const{defaultValue:t,queryString:a=!1,groupId:n}=e,u=d(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(!y({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]=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,u]=(0,s.Dv)(a);return[n,(0,l.useCallback)((e=>{a&&u.set(e)}),[a,u])]}({groupId:n}),g=(()=>{const e=o??c;return y({value:e,tabValues:u})?e:null})();(0,l.useLayoutEffect)((()=>{g&&i(g)}),[g]);return{selectedValue:r,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:u}))throw new Error(`Can't select invalid tab value=${e}`);i(e),p(e),h(e)}),[p,h,u]),tabValues:u}}var g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:i,selectValue:o,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),d=e=>{const t=e.currentTarget,a=s.indexOf(t),n=p[a].value;n!==i&&(c(t),o(n))},y=e=>{let t=null;switch(e.key){case"Enter":d(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.A)("tabs",{"tabs--block":a},t)},p.map((e=>{let{value:t,label:a,attributes:r}=e;return l.createElement("li",(0,n.A)({role:"tab",tabIndex:i===t?0:-1,"aria-selected":i===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},r,{className:(0,u.A)("tabs__item",f.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 T(e){const t=h(e);return l.createElement("div",{className:(0,u.A)("tabs-container",f.tabList)},l.createElement(b,(0,n.A)({},e,t)),l.createElement(v,(0,n.A)({},e,t)))}function P(e){const t=(0,g.A)();return l.createElement(T,(0,n.A)({key:String(t)},e))}},23255:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>m,frontMatter:()=>i,metadata:()=>p,toc:()=>c});var n=a(58168),l=(a(96540),a(15680)),u=(a(67443),a(11470)),r=a(19365);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-7.0.0/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-7.0.0/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/7.0.0/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/multiple-output-types.mdx",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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/7.0.0/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/7.0.0/symfony-bundle-advanced"}},s={},c=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],d={toc:c},y="wrapper";function m(e){let{components:t,...a}=e;return(0,l.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"In most cases, you have one PHP class and you want to map it to one GraphQL output type."),(0,l.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("h2",{id:"example"},"Example"),(0,l.yg)("p",null,"Here is an example. Say we are manipulating products. When I query a ",(0,l.yg)("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.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"Product"),' class is declaring a classic GraphQL output type named "Product".'),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"The ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType")," also declares an ",(0,l.yg)("a",{parentName:"p",href:"/docs/7.0.0/external-type-declaration"},'"external" type')," mapping the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class.\nBut pay special attention to the ",(0,l.yg)("inlineCode",{parentName:"p"},"@Type")," annotation."),(0,l.yg)("p",null,"First of all, we specify ",(0,l.yg)("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.yg)("p",null,"Then, we specify ",(0,l.yg)("inlineCode",{parentName:"p"},"default=false"),". This means that by default, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Product")," class should not be mapped to the ",(0,l.yg)("inlineCode",{parentName:"p"},"LimitedProductType"),".\nThis type will only be used when we explicitly request it."),(0,l.yg)("p",null,"Finally, we can write our requests:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'Notice how the "outputType" attribute is used in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@Field")," annotation to force the output type."),(0,l.yg)("p",null,"Is a result, when the end user calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"product")," query, we will have the possibility to fetch the ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," fields,\nbut if he calls the ",(0,l.yg)("inlineCode",{parentName:"p"},"products")," query, each product in the list will have a ",(0,l.yg)("inlineCode",{parentName:"p"},"name")," field but no ",(0,l.yg)("inlineCode",{parentName:"p"},"price")," field. We managed\nto successfully expose a different set of fields based on the query context."),(0,l.yg)("h2",{id:"extending-a-non-default-type"},"Extending a non-default type"),(0,l.yg)("p",null,"If you want to extend a type using the ",(0,l.yg)("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.yg)("p",null,"So instead of writing:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[ExtendType(class: Product::class)]\n"))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")))),(0,l.yg)("p",null,"you will write:"),(0,l.yg)(u.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'#[ExtendType(name: "LimitedProduct")]\n'))),(0,l.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @ExtendType(name="LimitedProduct")\n */\n')))),(0,l.yg)("p",null,'Notice how we use the "name" attribute instead of the "class" attribute in the ',(0,l.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e126d786.6b032437.js b/assets/js/e126d786.b4750660.js similarity index 99% rename from assets/js/e126d786.6b032437.js rename to assets/js/e126d786.b4750660.js index f1a399bbe..33ccac065 100644 --- a/assets/js/e126d786.6b032437.js +++ b/assets/js/e126d786.b4750660.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[776],{72348:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/4.2/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/4.2/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[776],{72348:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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}],d={toc:g},p="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(p,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/4.2/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"@MagicField")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/4.2/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e196b408.a78dca45.js b/assets/js/e196b408.c6be2aa7.js similarity index 98% rename from assets/js/e196b408.a78dca45.js rename to assets/js/e196b408.c6be2aa7.js index e281e14c3..45e4c0b5f 100644 --- a/assets/js/e196b408.a78dca45.js +++ b/assets/js/e196b408.c6be2aa7.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2],{67194:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var n=i(58168),r=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...i}=e;return(0,r.yg)(p,(0,n.A)({},l,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the #[Logged] attribute).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the #[Right] attribute).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2],{67194:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>u});var n=i(58168),r=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},u=[],l={toc:u},p="wrapper";function h(e){let{components:t,...i}=e;return(0,r.yg)(p,(0,n.A)({},l,i,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,r.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You need to write classes that implement these interfaces. Then, you must register those classes with GraphQLite.\nIt you are ",(0,r.yg)("a",{parentName:"p",href:"/docs/next/other-frameworks"},"using the ",(0,r.yg)("inlineCode",{parentName:"a"},"SchemaFactory")),", you can register your classes using:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"// Configure an authentication service (to resolve the #[Logged] attribute).\n$schemaFactory->setAuthenticationService($myAuthenticationService);\n// Configure an authorization service (to resolve the #[Right] attribute).\n$schemaFactory->setAuthorizationService($myAuthorizationService);\n")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e1b8bb84.db17b7db.js b/assets/js/e1b8bb84.d0fb13f2.js similarity index 99% rename from assets/js/e1b8bb84.db17b7db.js rename to assets/js/e1b8bb84.d0fb13f2.js index 7fda08f12..e806bd5e2 100644 --- a/assets/js/e1b8bb84.db17b7db.js +++ b/assets/js/e1b8bb84.d0fb13f2.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8055],{19365:(e,a,n)=>{n.d(a,{A:()=>i});var t=n(96540),r=n(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:a,hidden:n,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:n},a)}},11470:(e,a,n)=>{n.d(a,{A:()=>T});var t=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),p=n(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:n,attributes:t,default:r}}=e;return{value:a,label:n,attributes:t,default:r}}))}function d(e){const{values:a,children:n}=e;return(0,r.useMemo)((()=>{const e=a??c(n);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,n])}function g(e){let{value:a,tabValues:n}=e;return n.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:n}=e;const t=(0,o.W6)(),l=function(e){let{queryString:a=!1,groupId:n}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:n});return[(0,s.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(t.location.search);a.set(l,e),t.replace({...t.location,search:a.toString()})}),[l,t])]}function m(e){const{defaultValue:a,queryString:n=!1,groupId:t}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const t=n.find((e=>e.default))??n[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:a,tabValues:l}))),[s,u]=h({queryString:n,groupId:t}),[c,m]=function(e){let{groupId:a}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(a),[t,l]=(0,p.Dv)(n);return[t,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:t}),y=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,l]),tabValues:l}}var y=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const a=e.currentTarget,n=p.indexOf(a),t=u[n].value;t!==o&&(c(a),s(t))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;a=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;a=p[n]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":n},a)},u.map((e=>{let{value:a,label:n,attributes:i}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===a})}),n??a)})))}function b(e){let{lazy:a,children:n,selectedValue:t}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(a){const e=l.find((e=>e.props.value===t));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==t}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(v,(0,t.A)({},e,a)),r.createElement(b,(0,t.A)({},e,a)))}function T(e){const a=(0,y.A)();return r.createElement(w,(0,t.A)({key:String(a)},e))}},78122:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var t=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},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},g="wrapper";function h(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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'))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8055],{19365:(e,a,n)=>{n.d(a,{A:()=>i});var t=n(96540),r=n(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:a,hidden:n,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:n},a)}},11470:(e,a,n)=>{n.d(a,{A:()=>T});var t=n(58168),r=n(96540),l=n(20053),i=n(23104),o=n(56347),s=n(57485),u=n(31682),p=n(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:n,attributes:t,default:r}}=e;return{value:a,label:n,attributes:t,default:r}}))}function d(e){const{values:a,children:n}=e;return(0,r.useMemo)((()=>{const e=a??c(n);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,n])}function g(e){let{value:a,tabValues:n}=e;return n.some((e=>e.value===a))}function h(e){let{queryString:a=!1,groupId:n}=e;const t=(0,o.W6)(),l=function(e){let{queryString:a=!1,groupId:n}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:n});return[(0,s.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const a=new URLSearchParams(t.location.search);a.set(l,e),t.replace({...t.location,search:a.toString()})}),[l,t])]}function m(e){const{defaultValue:a,queryString:n=!1,groupId:t}=e,l=d(e),[i,o]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!g({value:a,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const t=n.find((e=>e.default))??n[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:a,tabValues:l}))),[s,u]=h({queryString:n,groupId:t}),[c,m]=function(e){let{groupId:a}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(a),[t,l]=(0,p.Dv)(n);return[t,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:t}),y=(()=>{const e=s??c;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&o(y)}),[y]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),u(e),m(e)}),[u,m,l]),tabValues:l}}var y=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:a,block:n,selectedValue:o,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const a=e.currentTarget,n=p.indexOf(a),t=u[n].value;t!==o&&(c(a),s(t))},g=e=>{let a=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=p.indexOf(e.currentTarget)+1;a=p[n]??p[0];break}case"ArrowLeft":{const n=p.indexOf(e.currentTarget)-1;a=p[n]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":n},a)},u.map((e=>{let{value:a,label:n,attributes:i}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:o===a?0:-1,"aria-selected":o===a,key:a,ref:e=>p.push(e),onKeyDown:g,onClick:d},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===a})}),n??a)})))}function b(e){let{lazy:a,children:n,selectedValue:t}=e;const l=(Array.isArray(n)?n:[n]).filter(Boolean);if(a){const e=l.find((e=>e.props.value===t));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},l.map(((e,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==t}))))}function w(e){const a=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(v,(0,t.A)({},e,a)),r.createElement(b,(0,t.A)({},e,a)))}function T(e){const a=(0,y.A)();return r.createElement(w,(0,t.A)({key:String(a)},e))}},78122:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>o,metadata:()=>u,toc:()=>c});var t=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},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},g="wrapper";function h(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,r.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,r.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,r.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your\ninput types."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,r.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,r.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,r.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,r.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,r.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,r.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,r.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,r.yg)("p",null,"Note: if you are using ",(0,r.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,r.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,r.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,r.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,r.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,r.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,r.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,r.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,r.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,r.yg)("p",null,"In short:"),(0,r.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,r.yg)("pre",null,(0,r.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,r.yg)("pre",null,(0,r.yg)("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'))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e29eb381.b515bb0f.js b/assets/js/e29eb381.db46fb20.js similarity index 99% rename from assets/js/e29eb381.b515bb0f.js rename to assets/js/e29eb381.db46fb20.js index cab3c97fc..5e7756536 100644 --- a/assets/js/e29eb381.b515bb0f.js +++ b/assets/js/e29eb381.db46fb20.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5884],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var r=a(96540),t=a(20053);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,t.A)(o.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>$});var r=a(58168),t=a(96540),o=a(20053),i=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);function p(e){return function(e){return t.Children.map(e,(e=>{if(!e||(0,t.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:a,attributes:r,default:t}}=e;return{value:n,label:a,attributes:r,default:t}}))}function d(e){const{values:n,children:a}=e;return(0,t.useMemo)((()=>{const e=n??p(a);return function(e){const n=(0,u.X)(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,a])}function h(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:a}=e;const r=(0,l.W6)(),o=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(o),(0,t.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 y(e){const{defaultValue:n,queryString:a=!1,groupId:r}=e,o=d(e),[i,l]=(0,t.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:a,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Dv)(a);return[r,(0,t.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:r}),g=(()=>{const e=s??p;return h({value:e,tabValues:o})?e:null})();(0,t.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:i,selectValue:(0,t.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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),d=e=>{const n=e.currentTarget,a=c.indexOf(n),r=u[a].value;r!==l&&(p(n),s(r))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;n=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;n=c[a]??c[c.length-1];break}}n?.focus()};return t.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":a},n)},u.map((e=>{let{value:n,label:a,attributes:i}=e;return t.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":l===n})}),a??n)})))}function w(e){let{lazy:n,children:a,selectedValue:r}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,t.cloneElement)(e,{className:"margin-top--md"}):null}return t.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,t.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=y(e);return t.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},t.createElement(b,(0,r.A)({},e,n)),t.createElement(w,(0,r.A)({},e,n)))}function $(e){const n=(0,g.A)();return t.createElement(v,(0,r.A)({key:String(n)},e))}},94667:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=a(58168),t=(a(96540),a(15680)),o=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},c={},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}],d={toc:p},h="wrapper";function m(e){let{components:n,...l}=e;return(0,t.yg)(h,(0,r.A)({},d,l,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("p",null,"If you are using ",(0,t.yg)("strong",{parentName:"p"},"Symfony 4.x"),", checkout the ",(0,t.yg)("a",{parentName:"p",href:"/docs/4.1/symfony-bundle"},"Symfony bundle"),"."),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"composer.json")),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"index.php")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/container.php")),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"src/Controllers/MyController.php")),(0,t.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,t.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/container.php")),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."),(0,t.yg)("p",null,(0,t.yg)("img",{src:a(67258).A,width:"1132",height:"352"})))}m.isMDXComponent=!0},67258:(e,n,a)=>{a.d(n,{A:()=>r});const r=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5884],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var r=a(96540),t=a(20053);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return r.createElement("div",{role:"tabpanel",className:(0,t.A)(o.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>$});var r=a(58168),t=a(96540),o=a(20053),i=a(23104),l=a(56347),s=a(57485),u=a(31682),c=a(89466);function p(e){return function(e){return t.Children.map(e,(e=>{if(!e||(0,t.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:a,attributes:r,default:t}}=e;return{value:n,label:a,attributes:r,default:t}}))}function d(e){const{values:n,children:a}=e;return(0,t.useMemo)((()=>{const e=n??p(a);return function(e){const n=(0,u.X)(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,a])}function h(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function m(e){let{queryString:n=!1,groupId:a}=e;const r=(0,l.W6)(),o=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(o),(0,t.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 y(e){const{defaultValue:n,queryString:a=!1,groupId:r}=e,o=d(e),[i,l]=(0,t.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!h({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const r=a.find((e=>e.default))??a[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:n,tabValues:o}))),[s,u]=m({queryString:a,groupId:r}),[p,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[r,o]=(0,c.Dv)(a);return[r,(0,t.useCallback)((e=>{a&&o.set(e)}),[a,o])]}({groupId:r}),g=(()=>{const e=s??p;return h({value:e,tabValues:o})?e:null})();(0,t.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:i,selectValue:(0,t.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 g=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:l,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),d=e=>{const n=e.currentTarget,a=c.indexOf(n),r=u[a].value;r!==l&&(p(n),s(r))},h=e=>{let n=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;n=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;n=c[a]??c[c.length-1];break}}n?.focus()};return t.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":a},n)},u.map((e=>{let{value:n,label:a,attributes:i}=e;return t.createElement("li",(0,r.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:h,onClick:d},i,{className:(0,o.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":l===n})}),a??n)})))}function w(e){let{lazy:n,children:a,selectedValue:r}=e;const o=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=o.find((e=>e.props.value===r));return e?(0,t.cloneElement)(e,{className:"margin-top--md"}):null}return t.createElement("div",{className:"margin-top--md"},o.map(((e,n)=>(0,t.cloneElement)(e,{key:n,hidden:e.props.value!==r}))))}function v(e){const n=y(e);return t.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},t.createElement(b,(0,r.A)({},e,n)),t.createElement(w,(0,r.A)({},e,n)))}function $(e){const n=(0,g.A)();return t.createElement(v,(0,r.A)({key:String(n)},e))}},94667:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>l,metadata:()=>u,toc:()=>p});var r=a(58168),t=(a(96540),a(15680)),o=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},c={},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}],d={toc:p},h="wrapper";function m(e){let{components:n,...l}=e;return(0,t.yg)(h,(0,r.A)({},d,l,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("p",null,"If you are using ",(0,t.yg)("strong",{parentName:"p"},"Symfony 4.x"),", checkout the ",(0,t.yg)("a",{parentName:"p",href:"/docs/4.1/symfony-bundle"},"Symfony bundle"),"."),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"composer.json")),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"index.php")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/container.php")),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"src/Controllers/MyController.php")),(0,t.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,t.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/container.php")),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."),(0,t.yg)("p",null,(0,t.yg)("img",{src:a(67258).A,width:"1132",height:"352"})))}m.isMDXComponent=!0},67258:(e,n,a)=>{a.d(n,{A:()=>r});const r=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/e2e51976.3c3c26bd.js b/assets/js/e2e51976.67c1d44f.js similarity index 99% rename from assets/js/e2e51976.3c3c26bd.js rename to assets/js/e2e51976.67c1d44f.js index 27d469917..ba69d5d53 100644 --- a/assets/js/e2e51976.3c3c26bd.js +++ b/assets/js/e2e51976.67c1d44f.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8945],{19365:(t,e,n)=>{n.d(e,{A:()=>i});var a=n(96540),r=n(20053);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.A)(o.tabItem,i),hidden:n},e)}},11470:(t,e,n)=>{n.d(e,{A:()=>w});var a=n(58168),r=n(96540),o=n(20053),i=n(23104),s=n(56347),l=n(57485),u=n(31682),c=n(89466);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.X)(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 g(t){let{queryString:e=!1,groupId:n}=t;const a=(0,s.W6)(),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.aZ)(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,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]=g({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.Dv)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),m=(()=>{const t=l??p;return h({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{m&&s(m)}),[m]);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),b(t)}),[u,b,o]),tabValues:o}}var m=n(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(t){let{className:e,block:n,selectedValue:s,selectValue:l,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),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.A)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.A)({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.A)("tabs__item",y.tabItem,i?.className,{"tabs__item--active":s===e})}),n??e)})))}function A(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=b(t);return r.createElement("div",{className:(0,o.A)("tabs-container",y.tabList)},r.createElement(f,(0,a.A)({},t,e)),r.createElement(A,(0,a.A)({},t,e)))}function w(t){const e=(0,m.A)();return r.createElement(v,(0,a.A)({key:String(e)},t))}},14841:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>l,default:()=>g,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),o=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(t){let{components:e,...n}=t;return(0,r.yg)(h,(0,a.A)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"Please note that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("strong",null,"Heads up!"),(0,r.yg)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",null,"PhpStorm via the ",(0,r.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.yg)("li",null,"Eclipse via the ",(0,r.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.yg)("li",null,"Netbeans has native support")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.yg)("p",null,"The same code can be written this way:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.yg)("p",null,"They support the same attributes too."),(0,r.yg)("p",null,"A few notable differences:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.yg)("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.yg)("p",null,"Let's take an example with the ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/autowiring"},(0,r.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))),(0,r.yg)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,r.yg)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8945],{19365:(t,e,n)=>{n.d(e,{A:()=>i});var a=n(96540),r=n(20053);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.A)(o.tabItem,i),hidden:n},e)}},11470:(t,e,n)=>{n.d(e,{A:()=>w});var a=n(58168),r=n(96540),o=n(20053),i=n(23104),s=n(56347),l=n(57485),u=n(31682),c=n(89466);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.X)(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 g(t){let{queryString:e=!1,groupId:n}=t;const a=(0,s.W6)(),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.aZ)(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,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]=g({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.Dv)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),m=(()=>{const t=l??p;return h({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{m&&s(m)}),[m]);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),b(t)}),[u,b,o]),tabValues:o}}var m=n(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(t){let{className:e,block:n,selectedValue:s,selectValue:l,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),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.A)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.A)({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.A)("tabs__item",y.tabItem,i?.className,{"tabs__item--active":s===e})}),n??e)})))}function A(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=b(t);return r.createElement("div",{className:(0,o.A)("tabs-container",y.tabList)},r.createElement(f,(0,a.A)({},t,e)),r.createElement(A,(0,a.A)({},t,e)))}function w(t){const e=(0,m.A)();return r.createElement(v,(0,a.A)({key:String(e)},t))}},14841:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>l,default:()=>g,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),o=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(t){let{components:e,...n}=t;return(0,r.yg)(h,(0,a.A)({},d,n,{components:e,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"Please note that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("strong",null,"Heads up!"),(0,r.yg)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",null,"PhpStorm via the ",(0,r.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.yg)("li",null,"Eclipse via the ",(0,r.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.yg)("li",null,"Netbeans has native support")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.yg)("p",null,"The same code can be written this way:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.yg)("p",null,"They support the same attributes too."),(0,r.yg)("p",null,"A few notable differences:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.yg)("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.yg)("p",null,"Let's take an example with the ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.0/autowiring"},(0,r.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field\n * @Autowire(for="$productRepository")\n */\npublic function getProduct(ProductRepository $productRepository) : Product {\n //...\n}\n')))),(0,r.yg)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,r.yg)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e347e63a.ae550287.js b/assets/js/e347e63a.0ae573d4.js similarity index 99% rename from assets/js/e347e63a.ae550287.js rename to assets/js/e347e63a.0ae573d4.js index 416fe8092..9e49fa6d2 100644 --- a/assets/js/e347e63a.ae550287.js +++ b/assets/js/e347e63a.0ae573d4.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5518],{19365:(e,t,n)=>{n.d(t,{A:()=>l});var a=n(96540),r=n(20053);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.A)(s.tabItem,l),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),s=n(20053),l=n(23104),o=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.A)({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.A)("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 T(e){const t=f(e);return r.createElement("div",{className:(0,s.A)("tabs-container",y.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,b.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},9619:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),s=(n(67443),n(11470)),l=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/6.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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([[5518],{19365:(e,t,n)=>{n.d(t,{A:()=>l});var a=n(96540),r=n(20053);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.A)(s.tabItem,l),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>w});var a=n(58168),r=n(96540),s=n(20053),l=n(23104),o=n(56347),i=n(57485),u=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(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(92303);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.a_)(),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.A)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:l}=e;return r.createElement("li",(0,a.A)({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.A)("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 T(e){const t=f(e);return r.createElement("div",{className:(0,s.A)("tabs-container",y.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function w(e){const t=(0,b.A)();return r.createElement(T,(0,a.A)({key:String(t)},e))}},9619:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>o,metadata:()=>u,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),s=(n(67443),n(11470)),l=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(d,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Consider a request where a user attached to a post must be returned:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n posts {\n id\n user {\n id\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of posts"),(0,r.yg)("li",{parentName:"ul"},"1 query per post to fetch the user")),(0,r.yg)("p",null,'Assuming we have "N" posts, we will make "N+1" queries.'),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/6.0/query-plan"},'"analyzing the query plan" documentation'),"."),(0,r.yg)("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.yg)("p",null,"Instead, GraphQLite offers an easier to implement solution: the ability to fetch all fields from a given type at once."),(0,r.yg)("h2",{id:"the-prefetch-method"},'The "prefetch" method'),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"input-arguments"},"Input arguments"),(0,r.yg)("p",null,"Field arguments can be set either on the @Field annotated method OR/AND on the prefetchMethod."),(0,r.yg)("p",null,"For instance:"),(0,r.yg)(s.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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/e39283a8.3578b356.js b/assets/js/e39283a8.70a0c24c.js similarity index 99% rename from assets/js/e39283a8.3578b356.js rename to assets/js/e39283a8.70a0c24c.js index f7ad0c3a8..e71636f3f 100644 --- a/assets/js/e39283a8.3578b356.js +++ b/assets/js/e39283a8.70a0c24c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1766],{30773:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-7.0.0/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-7.0.0/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/7.0.0/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/internals.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"docs",previous:{title:"Laravel specific features",permalink:"/docs/7.0.0/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/7.0.0/troubleshooting"}},l={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/7.0.0/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1766],{30773:(e,a,p)=>{p.r(a),p.d(a,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>y});var t=p(58168),r=(p(96540),p(15680)),n=p(67443);const i={id:"internals",title:"Internals",sidebar_label:"Internals"},s=void 0,o={unversionedId:"internals",id:"version-7.0.0/internals",title:"Internals",description:"Mapping types",source:"@site/versioned_docs/version-7.0.0/internals.md",sourceDirName:".",slug:"/internals",permalink:"/docs/7.0.0/internals",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/internals.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"internals",title:"Internals",sidebar_label:"Internals"},sidebar:"docs",previous:{title:"Laravel specific features",permalink:"/docs/7.0.0/laravel-package-advanced"},next:{title:"Troubleshooting",permalink:"/docs/7.0.0/troubleshooting"}},l={},y=[{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}],m={toc:y},g="wrapper";function u(e){let{components:a,...p}=e;return(0,r.yg)(g,(0,t.A)({},m,p,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"mapping-types"},"Mapping types"),(0,r.yg)("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.yg)("p",null,"GraphQLite contains 4 categories of type mappers:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Parameter mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Root type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"Recursive (class) type mappers")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("strong",{parentName:"li"},"(class) type mappers"))),(0,r.yg)(n.K,{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.yg)("h2",{id:"root-type-mappers"},"Root type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Root/RootTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RootTypeMapperInterface")),")"),(0,r.yg)("p",null,"These type mappers are the first type mappers called."),(0,r.yg)("p",null,"They are responsible for:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},'mapping scalar types (for instance mapping the "int" PHP type to GraphQL Integer type)'),(0,r.yg)("li",{parentName:"ul"},'detecting nullable/non-nullable types (for instance interpreting "?int" or "int|null")'),(0,r.yg)("li",{parentName:"ul"},"mapping list types (mapping a PHP array to a GraphQL list)"),(0,r.yg)("li",{parentName:"ul"},"mapping union types"),(0,r.yg)("li",{parentName:"ul"},"mapping enums")),(0,r.yg)("p",null,"Root type mappers have access to the ",(0,r.yg)("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.yg)("p",null,"GraphQLite provides 6 classes implementing ",(0,r.yg)("inlineCode",{parentName:"p"},"RootTypeMapperInterface"),":"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"NullableTypeMapperAdapter"),": a type mapper in charge of making GraphQL types non-nullable if the PHP type is non-nullable"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"IteratorTypeMapper"),": a type mapper in charge of iterable types (for instance: ",(0,r.yg)("inlineCode",{parentName:"li"},"MyIterator|User[]"),")"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompoundTypeMapper"),": a type mapper in charge of union types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"MyCLabsEnumTypeMapper"),": maps MyCLabs/enum types to GraphQL enum types (Deprecated: use native enums)"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"EnumTypeMapper"),": maps PHP enums to GraphQL enum types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"BaseTypeMapper"),': maps scalar types and lists. Passes the control to the "recursive type mappers" if an object is encountered.'),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("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.yg)("p",null,"Type mappers are organized in a chain; each type-mapper is responsible for calling the next type mapper."),(0,r.yg)(n.K,{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.yg)("h2",{id:"class-type-mappers"},"Class type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/TypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"TypeMapperInterface")),")"),(0,r.yg)("p",null,"Class type mappers are mapping PHP classes to GraphQL object types."),(0,r.yg)("p",null,"GraphQLite provide 3 default implementations:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper"),": a type mapper that delegates mapping to other type mappers using the Composite Design Pattern."),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"GlobTypeMapper"),": scans classes in a directory for the ",(0,r.yg)("inlineCode",{parentName:"li"},"@Type")," or ",(0,r.yg)("inlineCode",{parentName:"li"},"@ExtendType")," annotation and maps those to GraphQL types"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"PorpaginasTypeMapper"),": maps and class implementing the Porpaginas ",(0,r.yg)("inlineCode",{parentName:"li"},"Result")," interface to a ",(0,r.yg)("a",{parentName:"li",href:"/docs/7.0.0/pagination"},"special paginated type"),".")),(0,r.yg)("h3",{id:"registering-a-type-mapper-in-symfony"},"Registering a type mapper in Symfony"),(0,r.yg)("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.yg)("h3",{id:"registering-a-type-mapper-using-the-schemafactory"},"Registering a type mapper using the SchemaFactory"),(0,r.yg)("p",null,"If you are using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to bootstrap GraphQLite, you can register a type mapper using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addTypeMapper")," method."),(0,r.yg)("h2",{id:"recursive-type-mappers"},"Recursive type mappers"),(0,r.yg)("p",null,"(Classes implementing the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/RecursiveTypeMapperInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"RecursiveTypeMapperInterface")),")"),(0,r.yg)("p",null,"There is only one implementation of the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapperInterface"),": the ",(0,r.yg)("inlineCode",{parentName:"p"},"RecursiveTypeMapper"),"."),(0,r.yg)("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.yg)("p",null,'Imagine that class "B" extends class "A" and class "A" maps to GraphQL type "AType".'),(0,r.yg)("p",null,'Since "B" ',(0,r.yg)("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.yg)("h2",{id:"parameter-mapper-middlewares"},"Parameter mapper middlewares"),(0,r.yg)("p",null,'"Parameter middlewares" are used to decide what argument should be injected into a parameter.'),(0,r.yg)("p",null,"Let's have a look at a simple query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Query\n * @return Product[]\n */\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",null,"As you may know, ",(0,r.yg)("a",{parentName:"p",href:"/docs/7.0.0/query-plan"},"the ",(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfo")," object injected in this query comes from Webonyx/GraphQL-PHP library"),".\nGraphQLite knows that is must inject a ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," instance because it comes with a ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler"))," class\nthat implements the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ParameterMiddlewareInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterMiddlewareInterface")),")."),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()"),' method, or by tagging the\nservice as "graphql.parameter_middleware" if you are using the Symfony bundle.'),(0,r.yg)("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)"))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e45c611c.b3a00efb.js b/assets/js/e45c611c.ca35de63.js similarity index 99% rename from assets/js/e45c611c.b3a00efb.js rename to assets/js/e45c611c.ca35de63.js index 560b0f6e9..8996e4a23 100644 --- a/assets/js/e45c611c.b3a00efb.js +++ b/assets/js/e45c611c.ca35de63.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8107],{98697:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>s});var t=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:a,...n}=e;return(0,i.yg)(u,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,i.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,i.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,i.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your input types."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,i.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,i.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,i.yg)("p",null,"In your query, if you explicitly return an object that extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class, the query result will be wrapped in a\n"paginator" type.'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Notice that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,i.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,i.yg)("li",{parentName:"ul"},"you MUST add a ",(0,i.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,i.yg)("p",null,"Note: if you are using ",(0,i.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,i.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,i.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,i.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,i.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,i.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,i.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,i.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,i.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,i.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,i.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,i.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,i.yg)("p",null,"In short:"),(0,i.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,i.yg)("pre",null,(0,i.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,i.yg)("pre",null,(0,i.yg)("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'))))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8107],{98697:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>s});var t=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:a,...n}=e;return(0,i.yg)(u,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,i.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,i.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,i.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation to use Laravel validation rules in your input types."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation in any query / mutation / field / factory / decorator."),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"You can use any validation rule described in ",(0,i.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,i.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,i.yg)("p",null,"In your query, if you explicitly return an object that extends ",(0,i.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class, the query result will be wrapped in a\n"paginator" type.'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Notice that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,i.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,i.yg)("li",{parentName:"ul"},"you MUST add a ",(0,i.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,i.yg)("p",null,"Note: if you are using ",(0,i.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,i.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,i.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,i.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,i.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,i.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on each getter."),(0,i.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,i.yg)("inlineCode",{parentName:"p"},"@MagicField")," annotation to help you\nworking with magic properties."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,i.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation on the ",(0,i.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,i.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,i.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,i.yg)("p",null,"In short:"),(0,i.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,i.yg)("pre",null,(0,i.yg)("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.yg)("div",{class:"alert alert--success"},"This works:",(0,i.yg)("pre",null,(0,i.yg)("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'))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e4c5fdc3.2c80a6e5.js b/assets/js/e4c5fdc3.c11dcebd.js similarity index 98% rename from assets/js/e4c5fdc3.2c80a6e5.js rename to assets/js/e4c5fdc3.c11dcebd.js index fb9f4b1b2..b2e5665ec 100644 --- a/assets/js/e4c5fdc3.2c80a6e5.js +++ b/assets/js/e4c5fdc3.c11dcebd.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4664],{5176:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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([[4664],{5176:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>l,contentTitle:()=>o,default:()=>c,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=t(58168),n=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:a,...t}=e;return(0,n.yg)(u,(0,r.A)({},m,t,{components:a,mdxType:"MDXLayout"}),(0,n.yg)("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.yg)("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.yg)("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.yg)("p",null,"To avoid being bound to our backward compatibility promise, such features can be marked as ",(0,n.yg)("strong",{parentName:"p"},"unstable")," or ",(0,n.yg)("strong",{parentName:"p"},"experimental")," and their classes and methods are marked with the ",(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," tag."),(0,n.yg)("p",null,(0,n.yg)("inlineCode",{parentName:"p"},"@unstable")," or ",(0,n.yg)("inlineCode",{parentName:"p"},"@experimental")," classes / methods will ",(0,n.yg)("strong",{parentName:"p"},"not break")," in a patch release, but ",(0,n.yg)("em",{parentName:"p"},"may be broken")," in a minor version."),(0,n.yg)("p",null,"As a rule of thumb:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"If you are a GraphQLite user (using GraphQLite mainly through its annotations), we guarantee strict semantic versioning"),(0,n.yg)("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.yg)("p",null,"Said otherwise:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are a GraphQLite user, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a major version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "^4"\n }\n}\n'))),(0,n.yg)("li",{parentName:"ul"},(0,n.yg)("p",{parentName:"li"},"If you are extending the GraphQLite ecosystem, in your ",(0,n.yg)("inlineCode",{parentName:"p"},"composer.json"),", target a minor version:"),(0,n.yg)("pre",{parentName:"li"},(0,n.yg)("code",{parentName:"pre",className:"language-json"},'{\n "require": {\n "thecodingmachine/graphqlite": "~4.1.0"\n }\n}\n')))),(0,n.yg)("p",null,"Finally, classes / methods annotated with the ",(0,n.yg)("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.52fa3839.js b/assets/js/e5d0e3cb.89229e6e.js similarity index 99% rename from assets/js/e5d0e3cb.52fa3839.js rename to assets/js/e5d0e3cb.89229e6e.js index b5feeaa7b..d8917ee80 100644 --- a/assets/js/e5d0e3cb.52fa3839.js +++ b/assets/js/e5d0e3cb.89229e6e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4978],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>q});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),u=n(56347),s=n(57485),i=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&u(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}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":u===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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function q(e){const t=(0,y.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},60967:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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([[4978],{19365:(e,t,n)=>{n.d(t,{A:()=>o});var a=n(96540),r=n(20053);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.A)(l.tabItem,o),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>q});var a=n(58168),r=n(96540),l=n(20053),o=n(23104),u=n(56347),s=n(57485),i=n(31682),c=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(n);return[a,(0,r.useCallback)((e=>{n&&l.set(e)}),[n,l])]}({groupId:a}),y=(()=>{const e=s??p;return h({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{y&&u(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}`);u(e),i(e),f(e)}),[i,f,l]),tabValues:l}}var y=n(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function g(e){let{className:t,block:n,selectedValue:u,selectValue:s,tabValues:i}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),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.A)("tabs",{"tabs--block":n},t)},i.map((e=>{let{value:t,label:n,attributes:o}=e;return r.createElement("li",(0,a.A)({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.A)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":u===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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(g,(0,a.A)({},e,t)),r.createElement(v,(0,a.A)({},e,t)))}function q(e){const t=(0,y.A)();return r.createElement(w,(0,a.A)({key:String(t)},e))}},60967:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>s,default:()=>m,frontMatter:()=>u,metadata:()=>i,toc:()=>p});var a=n(58168),r=(n(96540),n(15680)),l=(n(67443),n(11470)),o=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"the-problem"},"The problem"),(0,r.yg)("p",null,'GraphQL naive implementations often suffer from the "N+1" problem.'),(0,r.yg)("p",null,"Let's have a look at the following query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"{\n products {\n name\n manufacturer {\n name\n }\n }\n}\n")),(0,r.yg)("p",null,"A naive implementation will do this:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"1 query to fetch the list of products"),(0,r.yg)("li",{parentName:"ul"},"1 query per product to fetch the manufacturer")),(0,r.yg)("p",null,'Assuming we have "N" products, we will make "N+1" queries.'),(0,r.yg)("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.yg)("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.yg)("p",null,"With GraphQLite, you can answer this question by tapping into the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object."),(0,r.yg)("h2",{id:"fetching-the-query-plan"},"Fetching the query plan"),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},"As of the writing of this documentation, the ",(0,r.yg)("code",null,"ResolveInfo")," class is useful but somewhat limited. The ",(0,r.yg)("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.ca62b12f.js b/assets/js/e5d7b215.1d93a1b0.js similarity index 98% rename from assets/js/e5d7b215.ca62b12f.js rename to assets/js/e5d7b215.1d93a1b0.js index d7c9ad8ca..768ead2b0 100644 --- a/assets/js/e5d7b215.ca62b12f.js +++ b/assets/js/e5d7b215.1d93a1b0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9040],{51546:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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,...i}=e;return(0,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/next/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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([[9040],{51546:(e,r,i)=>{i.r(r),i.d(r,{assets:()=>p,contentTitle:()=>o,default:()=>h,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var n=i(58168),t=(i(96540),i(15680));i(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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,...i}=e;return(0,t.yg)(d,(0,n.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("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,t.yg)("p",null,"If your framework is compatible with ",(0,t.yg)("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,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"/docs/next/other-frameworks"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,t.yg)("p",null,(0,t.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,t.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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.6f5afd18.js b/assets/js/e617c97b.1accdd02.js similarity index 99% rename from assets/js/e617c97b.6f5afd18.js rename to assets/js/e617c97b.1accdd02.js index 6e7e40c75..47b3d1c4a 100644 --- a/assets/js/e617c97b.6f5afd18.js +++ b/assets/js/e617c97b.1accdd02.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3449],{26693:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var t=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:a,...n}=e;return(0,i.yg)(u,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"41"},"4.1"),(0,i.yg)("p",null,"Breaking change:"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("p",null,"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("p",null,"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("p",null,"Miscellaneous:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"40"},"4.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("p",null,"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/error-handling"},"GraphQL errors")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")),(0,i.yg)("li",{parentName:"ul"},'You can specify the HTTP response code to send with a given error, and the errors "extensions" section'),(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can map ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory")," annotations)"),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/extend_input_type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("p",null,"Symfony:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("p",null,"Laravel:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("p",null,"Internals:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3449],{26693:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var t=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:a,...n}=e;return(0,i.yg)(u,(0,t.A)({},d,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"41"},"4.1"),(0,i.yg)("p",null,"Breaking change:"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("p",null,"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("p",null,"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("p",null,"Miscellaneous:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"40"},"4.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("p",null,"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/error-handling"},"GraphQL errors")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException")),(0,i.yg)("li",{parentName:"ul"},'You can specify the HTTP response code to send with a given error, and the errors "extensions" section'),(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can map ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory")," annotations)"),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/extend_input_type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("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.yg)("p",null,"New framework specific features:"),(0,i.yg)("p",null,"Symfony:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("p",null,"Laravel:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/4.1/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("p",null,"Internals:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e63ebe23.04f40872.js b/assets/js/e63ebe23.45e84105.js similarity index 99% rename from assets/js/e63ebe23.04f40872.js rename to assets/js/e63ebe23.45e84105.js index a40b5b841..af6b1c3ce 100644 --- a/assets/js/e63ebe23.04f40872.js +++ b/assets/js/e63ebe23.45e84105.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8260],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),l=n(20053);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.A)(r.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>$});var a=n(58168),l=n(96540),r=n(20053),i=n(23104),o=n(56347),u=n(57485),p=n(31682),s=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function g(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.W6)(),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.aZ)(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 m(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(!y({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]=g({queryString:n,groupId:a}),[c,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Dv)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),h=(()=>{const e=u??c;return y({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),m(e)}),[p,m,r]),tabValues:r}}var h=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},y=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.A)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},i,{className:(0,r.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(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 I(e){const t=m(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,t)),l.createElement(v,(0,a.A)({},e,t)))}function $(e){const t=(0,h.A)();return l.createElement(I,(0,a.A)({key:String(t)},e))}},39702:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>g,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(58168),l=(n(96540),n(15680)),r=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function g(e){let{components:t,...n}=e;return(0,l.yg)(y,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.yg)("p",null,"Your GraphQL query might look like this:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,l.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,l.yg)("a",{parentName:"p",href:"#input-attribute"},(0,l.yg)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,l.yg)("a",{parentName:"p",href:"#factory"},"Factory method"),"."),(0,l.yg)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,l.yg)("p",null,"Using the ",(0,l.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"Now if you call the ",(0,l.yg)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,l.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.yg)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,l.yg)("p",null,"There are some important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},"The ",(0,l.yg)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized on properties for Input Type, as well as setters."),(0,l.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.yg)("ul",{parentName:"li"},(0,l.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,l.yg)("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.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,l.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on the setter, instead of the property, allowing you to have use many other attributes (",(0,l.yg)("inlineCode",{parentName:"li"},"Security"),", ",(0,l.yg)("inlineCode",{parentName:"li"},"Right"),", ",(0,l.yg)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,l.yg)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,l.yg)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,l.yg)("li",{parentName:"ul"},"It's advised to use the ",(0,l.yg)("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.yg)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,l.yg)("p",null,"Simple usage of the ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," class."),(0,l.yg)("p",null,"You can add multiple ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"There are 2 input types added to the ",(0,l.yg)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,l.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.yg)("p",null,"Note that ",(0,l.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.yg)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.yg)("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.yg)("h2",{id:"factory"},"Factory"),(0,l.yg)("p",null,"A ",(0,l.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.yg)("p",null,"Here is an example of factory:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.yg)("p",null,"A few important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.yg)("p",null,"You can use the ",(0,l.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.yg)("p",null,"Here is an annotated sample:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("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.yg)("p",null,"Image your ",(0,l.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"With the ",(0,l.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.yg)("p",null,"To be able to hide an argument, the argument must have a default value."))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8260],{19365:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(96540),l=n(20053);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.A)(r.tabItem,i),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>$});var a=n(58168),l=n(96540),r=n(20053),i=n(23104),o=n(56347),u=n(57485),p=n(31682),s=n(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function g(e){let{queryString:t=!1,groupId:n}=e;const a=(0,o.W6)(),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.aZ)(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 m(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(!y({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]=g({queryString:n,groupId:a}),[c,m]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,s.Dv)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,r])]}({groupId:a}),h=(()=>{const e=u??c;return y({value:e,tabValues:r})?e:null})();(0,l.useLayoutEffect)((()=>{h&&o(h)}),[h]);return{selectedValue:i,selectValue:(0,l.useCallback)((e=>{if(!y({value:e,tabValues:r}))throw new Error(`Can't select invalid tab value=${e}`);o(e),p(e),m(e)}),[p,m,r]),tabValues:r}}var h=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:u,tabValues:p}=e;const s=[],{blockElementScrollPositionUntilNextRender:c}=(0,i.a_)(),d=e=>{const t=e.currentTarget,n=s.indexOf(t),a=p[n].value;a!==o&&(c(t),u(a))},y=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.A)("tabs",{"tabs--block":n},t)},p.map((e=>{let{value:t,label:n,attributes:i}=e;return l.createElement("li",(0,a.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>s.push(e),onKeyDown:y,onClick:d},i,{className:(0,r.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":o===t})}),n??t)})))}function v(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 I(e){const t=m(e);return l.createElement("div",{className:(0,r.A)("tabs-container",f.tabList)},l.createElement(b,(0,a.A)({},e,t)),l.createElement(v,(0,a.A)({},e,t)))}function $(e){const t=(0,h.A)();return l.createElement(I,(0,a.A)({key:String(t)},e))}},39702:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>u,default:()=>g,frontMatter:()=>o,metadata:()=>p,toc:()=>c});var a=n(58168),l=(n(96540),n(15680)),r=(n(67443),n(11470)),i=n(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function g(e){let{components:t,...n}=e;return(0,l.yg)(y,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,l.yg)("p",null,"Let's assume you are developing an API that returns a list of cities around a location."),(0,l.yg)("p",null,"Your GraphQL query might look like this:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"If you try to run this code, you will get the following error:"),(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre"},'CannotMapTypeException: cannot map class "Location" to a known GraphQL input type. Check your TypeMapper configuration.\n')),(0,l.yg)("p",null,"You are running into this error because GraphQLite does not know how to handle the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object."),(0,l.yg)("p",null,"In GraphQL, an object passed in parameter of a query or mutation (or any field) is called an ",(0,l.yg)("strong",{parentName:"p"},"Input Type"),"."),(0,l.yg)("p",null,"There are two ways for declaring that type, in GraphQLite: using the ",(0,l.yg)("a",{parentName:"p",href:"#input-attribute"},(0,l.yg)("inlineCode",{parentName:"a"},"#[Input]")," attribute")," or a ",(0,l.yg)("a",{parentName:"p",href:"#factory"},"Factory method"),"."),(0,l.yg)("h2",{id:"input-attribute"},"#","[","Input","]"," Attribute"),(0,l.yg)("p",null,"Using the ",(0,l.yg)("inlineCode",{parentName:"p"},"#[Input]")," attribute, we can transform the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," class, in the example above, into an input type. Just add the ",(0,l.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute to the corresponding properties:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"Now if you call the ",(0,l.yg)("inlineCode",{parentName:"p"},"getCities")," query, from the controller in the first example, the ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," object will be automatically instantiated with the user provided, ",(0,l.yg)("inlineCode",{parentName:"p"},"latitude")," / ",(0,l.yg)("inlineCode",{parentName:"p"},"longitude")," properties, and passed to the controller as a parameter."),(0,l.yg)("p",null,"There are some important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},"The ",(0,l.yg)("inlineCode",{parentName:"li"},"@Field")," annotation is recognized on properties for Input Type, as well as setters."),(0,l.yg)("li",{parentName:"ul"},"There are 3 ways for fields to be resolved:",(0,l.yg)("ul",{parentName:"li"},(0,l.yg)("li",{parentName:"ul"},"Via constructor if corresponding properties are mentioned as parameters with the same names - exactly as in the example above."),(0,l.yg)("li",{parentName:"ul"},"If properties are public, they will be just set without any additional effort - no constructor required."),(0,l.yg)("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.yg)("inlineCode",{parentName:"li"},"setLatitude(float $latitude)"),". You can also put the ",(0,l.yg)("inlineCode",{parentName:"li"},"@Field")," annotation on the setter, instead of the property, allowing you to have use many other attributes (",(0,l.yg)("inlineCode",{parentName:"li"},"Security"),", ",(0,l.yg)("inlineCode",{parentName:"li"},"Right"),", ",(0,l.yg)("inlineCode",{parentName:"li"},"Autowire"),", etc.)."))),(0,l.yg)("li",{parentName:"ul"},"For validation of these Input Types, see the ",(0,l.yg)("a",{parentName:"li",href:"validation#custom-inputtype-validation"},"Custom InputType Validation section"),"."),(0,l.yg)("li",{parentName:"ul"},"It's advised to use the ",(0,l.yg)("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.yg)("h3",{id:"multiple-input-types-from-the-same-class"},"Multiple Input Types from the same class"),(0,l.yg)("p",null,"Simple usage of the ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"LocationInput")," for ",(0,l.yg)("inlineCode",{parentName:"p"},"Location")," class."),(0,l.yg)("p",null,"You can add multiple ",(0,l.yg)("inlineCode",{parentName:"p"},"@Input")," annotations to the same class, give them different names and link different fields.\nConsider the following example:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"There are 2 input types added to the ",(0,l.yg)("inlineCode",{parentName:"p"},"UserInput")," class: ",(0,l.yg)("inlineCode",{parentName:"p"},"CreateUserInput")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"UpdateUserInput"),". A few notes:"),(0,l.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input will be used by default for this class."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"username")," is created for both input types, and it is required because the property type is not nullable."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"email")," will appear only for ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," input."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"password")," will appear for both. For ",(0,l.yg)("inlineCode",{parentName:"li"},"CreateUserInput")," it'll be the required field and for ",(0,l.yg)("inlineCode",{parentName:"li"},"UpdateUserInput")," optional."),(0,l.yg)("li",{parentName:"ul"},"Field ",(0,l.yg)("inlineCode",{parentName:"li"},"age")," is optional for both input types.")),(0,l.yg)("p",null,"Note that ",(0,l.yg)("inlineCode",{parentName:"p"},"update: true")," argument for ",(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"UpdateUserInput")," and set only ",(0,l.yg)("inlineCode",{parentName:"p"},"username")," the other ones will be ignored.\nIn PHP 7 they will be set to ",(0,l.yg)("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.yg)("h2",{id:"factory"},"Factory"),(0,l.yg)("p",null,"A ",(0,l.yg)("strong",{parentName:"p"},"Factory")," is a method that takes in parameter all the fields of the input type and return an object."),(0,l.yg)("p",null,"Here is an example of factory:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"and now, you can run query like this:"),(0,l.yg)("pre",null,(0,l.yg)("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.yg)("ul",null,(0,l.yg)("li",{parentName:"ul"},"Factories must be declared with the ",(0,l.yg)("strong",{parentName:"li"},"@Factory")," annotation."),(0,l.yg)("li",{parentName:"ul"},"The parameters of the factories are the field of the GraphQL input type")),(0,l.yg)("p",null,"A few important things to notice:"),(0,l.yg)("ul",null,(0,l.yg)("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.yg)("li",{parentName:"ul"},"We recommend that you put the factories in the same directories as the types.")),(0,l.yg)("h3",{id:"specifying-the-input-type-name"},"Specifying the input type name"),(0,l.yg)("p",null,"The GraphQL input type name is derived from the return type of the factory."),(0,l.yg)("p",null,'Given the factory below, the return type is "Location", therefore, the GraphQL input type will be named "LocationInput".'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,'In case you want to override the input type name, you can use the "name" attribute of the @Factory annotation:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},"#[Factory(name: 'MyNewInputName', default: true)]\n"))),(0,l.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Factory(name="MyNewInputName", default=true)\n */\n')))),(0,l.yg)("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.yg)("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.yg)("h3",{id:"forcing-an-input-type"},"Forcing an input type"),(0,l.yg)("p",null,"You can use the ",(0,l.yg)("inlineCode",{parentName:"p"},"@UseInputType")," annotation to force an input type of a parameter."),(0,l.yg)("p",null,'Let\'s say you want to force a parameter to be of type "ID", you can use this:'),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"declaring-several-input-types-for-the-same-php-class"},"Declaring several input types for the same PHP class"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("p",null,"There are situations where a given PHP class might use one factory or another depending on the context."),(0,l.yg)("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.yg)("inlineCode",{parentName:"p"},"@UseInputType")," and ",(0,l.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation to achieve your goal."),(0,l.yg)("p",null,"Here is an annotated sample:"),(0,l.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("h3",{id:"ignoring-some-parameters"},"Ignoring some parameters"),(0,l.yg)("small",null,"Available in GraphQLite 4.0+"),(0,l.yg)("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.yg)("p",null,"Image your ",(0,l.yg)("inlineCode",{parentName:"p"},"getProductById")," has an additional ",(0,l.yg)("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.yg)(r.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,l.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,l.yg)("pre",null,(0,l.yg)("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.yg)("p",null,"With the ",(0,l.yg)("inlineCode",{parentName:"p"},"@HideParameter")," annotation, you can choose to remove from the GraphQL schema any argument."),(0,l.yg)("p",null,"To be able to hide an argument, the argument must have a default value."))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e6858589.12658908.js b/assets/js/e6858589.72e37720.js similarity index 96% rename from assets/js/e6858589.12658908.js rename to assets/js/e6858589.72e37720.js index 9810a5a56..0a8d9cb1c 100644 --- a/assets/js/e6858589.12658908.js +++ b/assets/js/e6858589.72e37720.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7143],{42495:(e,o,t)=>{t.r(o),t.d(o,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>r,metadata:()=>a,toc:()=>u});var n=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},u=[],d={toc:u},c="wrapper";function g(e){let{components:o,...t}=e;return(0,i.yg)(c,(0,n.A)({},d,t,{components:o,mdxType:"MDXLayout"}),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7143],{42495:(e,o,t)=>{t.r(o),t.d(o,{assets:()=>l,contentTitle:()=>s,default:()=>g,frontMatter:()=>r,metadata:()=>a,toc:()=>u});var n=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},u=[],d={toc:u},c="wrapper";function g(e){let{components:o,...t}=e;return(0,i.yg)(c,(0,n.A)({},d,t,{components:o,mdxType:"MDXLayout"}),(0,i.yg)("p",null,(0,i.yg)("strong",{parentName:"p"},"Error: Maximum function nesting level of '100' reached")),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre"},"xdebug.max_nesting_level=500\n")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e688cd7e.064a3472.js b/assets/js/e688cd7e.328d42a5.js similarity index 99% rename from assets/js/e688cd7e.064a3472.js rename to assets/js/e688cd7e.328d42a5.js index 29c825a8f..b0b7bf135 100644 --- a/assets/js/e688cd7e.064a3472.js +++ b/assets/js/e688cd7e.328d42a5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4840],{19365:(t,e,n)=>{n.d(e,{A:()=>i});var a=n(96540),r=n(20053);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.A)(o.tabItem,i),hidden:n},e)}},11470:(t,e,n)=>{n.d(e,{A:()=>w});var a=n(58168),r=n(96540),o=n(20053),i=n(23104),s=n(56347),l=n(57485),u=n(31682),c=n(89466);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.X)(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 g(t){let{queryString:e=!1,groupId:n}=t;const a=(0,s.W6)(),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.aZ)(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,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]=g({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.Dv)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),m=(()=>{const t=l??p;return h({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{m&&s(m)}),[m]);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),b(t)}),[u,b,o]),tabValues:o}}var m=n(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(t){let{className:e,block:n,selectedValue:s,selectValue:l,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),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.A)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.A)({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.A)("tabs__item",y.tabItem,i?.className,{"tabs__item--active":s===e})}),n??e)})))}function A(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=b(t);return r.createElement("div",{className:(0,o.A)("tabs-container",y.tabList)},r.createElement(f,(0,a.A)({},t,e)),r.createElement(A,(0,a.A)({},t,e)))}function w(t){const e=(0,m.A)();return r.createElement(v,(0,a.A)({key:String(e)},t))}},52708:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>i,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>u});var a=n(58168),r=(n(96540),n(15680));n(67443),n(11470),n(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.1/migrating"},next:{title:"Annotations reference",permalink:"/docs/6.1/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.yg)(p,(0,a.A)({},c,n,{components:e,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"Please note that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("strong",null,"Heads up!"),(0,r.yg)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",null,"PhpStorm via the ",(0,r.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.yg)("li",null,"Eclipse via the ",(0,r.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.yg)("li",null,"Netbeans has native support")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.yg)("p",null,"The same code can be written this way:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.yg)("p",null,"They support the same attributes too."),(0,r.yg)("p",null,"A few notable differences:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.yg)("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.yg)("p",null,"Let's take an example with the ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.1/autowiring"},(0,r.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")),(0,r.yg)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,r.yg)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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([[4840],{19365:(t,e,n)=>{n.d(e,{A:()=>i});var a=n(96540),r=n(20053);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.A)(o.tabItem,i),hidden:n},e)}},11470:(t,e,n)=>{n.d(e,{A:()=>w});var a=n(58168),r=n(96540),o=n(20053),i=n(23104),s=n(56347),l=n(57485),u=n(31682),c=n(89466);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.X)(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 g(t){let{queryString:e=!1,groupId:n}=t;const a=(0,s.W6)(),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.aZ)(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,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]=g({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.Dv)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),m=(()=>{const t=l??p;return h({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{m&&s(m)}),[m]);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),b(t)}),[u,b,o]),tabValues:o}}var m=n(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function f(t){let{className:e,block:n,selectedValue:s,selectValue:l,tabValues:u}=t;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),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.A)("tabs",{"tabs--block":n},e)},u.map((t=>{let{value:e,label:n,attributes:i}=t;return r.createElement("li",(0,a.A)({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.A)("tabs__item",y.tabItem,i?.className,{"tabs__item--active":s===e})}),n??e)})))}function A(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=b(t);return r.createElement("div",{className:(0,o.A)("tabs-container",y.tabList)},r.createElement(f,(0,a.A)({},t,e)),r.createElement(A,(0,a.A)({},t,e)))}function w(t){const e=(0,m.A)();return r.createElement(v,(0,a.A)({key:String(e)},t))}},52708:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>i,default:()=>d,frontMatter:()=>o,metadata:()=>s,toc:()=>u});var a=n(58168),r=(n(96540),n(15680));n(67443),n(11470),n(19365);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.1/migrating"},next:{title:"Annotations reference",permalink:"/docs/6.1/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.yg)(p,(0,a.A)({},c,n,{components:e,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+)."),(0,r.yg)("h2",{id:"doctrine-annotations"},"Doctrine annotations"),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Deprecated!")," Doctrine annotations are deprecated in favor of native PHP 8 attributes. Support will be dropped in a future release."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html"},"doctrine/annotation")," library."),(0,r.yg)("p",null,"Using Doctrine annotations, you write annotations in your docblocks:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n/**\n * @Type\n */\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"Please note that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The annotation is added in a ",(0,r.yg)("strong",{parentName:"li"},"docblock"),' (a comment starting with "',(0,r.yg)("inlineCode",{parentName:"li"},"/**"),'")'),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"Type")," part is actually a class. It must be declared in the ",(0,r.yg)("inlineCode",{parentName:"li"},"use")," statements at the top of your file.")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("strong",null,"Heads up!"),(0,r.yg)("p",null,"Some IDEs provide support for Doctrine annotations:"),(0,r.yg)("ul",null,(0,r.yg)("li",null,"PhpStorm via the ",(0,r.yg)("a",{href:"https://plugins.jetbrains.com/plugin/7320-php-annotations"},"PHP Annotations Plugin")),(0,r.yg)("li",null,"Eclipse via the ",(0,r.yg)("a",{href:"https://marketplace.eclipse.org/content/symfony-plugin"},"Symfony 2 Plugin")),(0,r.yg)("li",null,"Netbeans has native support")),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre"},"We strongly recommend using an IDE that has Doctrine annotations support.\n"))),(0,r.yg)("h2",{id:"php-8-attributes"},"PHP 8 attributes"),(0,r.yg)("p",null,'Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.'),(0,r.yg)("p",null,"The same code can be written this way:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Annotations\\Type;\n\n#[Type]\nclass MyType\n{\n}\n")),(0,r.yg)("p",null,"GraphQLite v4.1+ has support for PHP 8 attributes."),(0,r.yg)("p",null,"The Doctrine annotation class and the PHP 8 attribute class is ",(0,r.yg)("strong",{parentName:"p"},"the same")," (so you will be using the same ",(0,r.yg)("inlineCode",{parentName:"p"},"use")," statement at the top of your file)."),(0,r.yg)("p",null,"They support the same attributes too."),(0,r.yg)("p",null,"A few notable differences:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the ",(0,r.yg)("inlineCode",{parentName:"li"},"annotations")," attribute of ",(0,r.yg)("inlineCode",{parentName:"li"},"@MagicField")," and ",(0,r.yg)("inlineCode",{parentName:"li"},"@SourceField"),"."),(0,r.yg)("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.yg)("p",null,"Let's take an example with the ",(0,r.yg)("a",{parentName:"p",href:"/docs/6.1/autowiring"},(0,r.yg)("inlineCode",{parentName:"a"},"#Autowire")," attribute"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getProduct(#[Autowire] ProductRepository $productRepository) : Product {\n //...\n}\n")),(0,r.yg)("h2",{id:"migrating-from-doctrine-annotations-to-php-8-attributes"},"Migrating from Doctrine annotations to PHP 8 attributes"),(0,r.yg)("p",null,"The good news is that you can easily migrate from Doctrine annotations to PHP 8 attributes using the amazing, ",(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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/e68b092b.f74e87f3.js b/assets/js/e68b092b.47aa1931.js similarity index 99% rename from assets/js/e68b092b.f74e87f3.js rename to assets/js/e68b092b.47aa1931.js index 1f39ad776..a73f0d194 100644 --- a/assets/js/e68b092b.f74e87f3.js +++ b/assets/js/e68b092b.47aa1931.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8173],{70571:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(58168),a=(t(96540),t(15680));t(67443);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-7.0.0/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-7.0.0/field-middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/7.0.0/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/field-middlewares.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"docs",previous:{title:"Custom types",permalink:"/docs/7.0.0/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/7.0.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.yg)(p,(0,i.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:t(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("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.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,n,t)=>{t.d(n,{A:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8173],{70571:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(58168),a=(t(96540),t(15680));t(67443);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-7.0.0/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-7.0.0/field-middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/7.0.0/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-7.0.0/field-middlewares.md",tags:[],version:"7.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"docs",previous:{title:"Custom types",permalink:"/docs/7.0.0/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/7.0.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.yg)(p,(0,i.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:t(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("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.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,n,t)=>{t.d(n,{A:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/e7672013.48d425a0.js b/assets/js/e7672013.44846702.js similarity index 98% rename from assets/js/e7672013.48d425a0.js rename to assets/js/e7672013.44846702.js index 8c453d14e..dd934ca05 100644 --- a/assets/js/e7672013.48d425a0.js +++ b/assets/js/e7672013.44846702.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2600],{57385:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>r,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>l});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:t,...n}=e;return(0,i.yg)(c,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("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.yg)("br",null),"See ",(0,i.yg)("a",{href:"#connecting-graphqlite-to-your-framework-s-security-module"},"Connecting GraphQLite to your framework's security module"),"."),(0,i.yg)("h2",{id:"logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,i.yg)("p",null,"GraphQLite exposes two annotations (",(0,i.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, the query ",(0,i.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,i.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,i.yg)("p",null,(0,i.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,i.yg)("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.yg)("h2",{id:"constant-schemas"},"Constant schemas"),(0,i.yg)("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.yg)("p",null,"If you want to keep a constant schema, you can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation that contains the value that\nwill be returned for user with insufficient rights."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h2",{id:"connecting-graphqlite-to-your-frameworks-security-module"},"Connecting GraphQLite to your framework's security module"),(0,i.yg)("div",{class:"alert alert--info"},"This step is NOT necessary for user using GraphQLite through the Symfony Bundle"),(0,i.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,i.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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')))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2600],{57385:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>r,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>l});var a=n(58168),i=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:t,...n}=e;return(0,i.yg)(c,(0,a.A)({},h,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("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.yg)("br",null),"See ",(0,i.yg)("a",{href:"#connecting-graphqlite-to-your-framework-s-security-module"},"Connecting GraphQLite to your framework's security module"),"."),(0,i.yg)("h2",{id:"logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,i.yg)("p",null,"GraphQLite exposes two annotations (",(0,i.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, the query ",(0,i.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,i.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,i.yg)("p",null,(0,i.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,i.yg)("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.yg)("h2",{id:"constant-schemas"},"Constant schemas"),(0,i.yg)("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.yg)("p",null,"If you want to keep a constant schema, you can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation that contains the value that\nwill be returned for user with insufficient rights."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h2",{id:"connecting-graphqlite-to-your-frameworks-security-module"},"Connecting GraphQLite to your framework's security module"),(0,i.yg)("div",{class:"alert alert--info"},"This step is NOT necessary for user using GraphQLite through the Symfony Bundle"),(0,i.yg)("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.yg)("p",null,"To plug GraphQLite to your framework's security mechanism, you will have to provide two classes implementing:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthenticationServiceInterface")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Security\\AuthorizationServiceInterface"))),(0,i.yg)("p",null,"Those two interfaces act as adapters between GraphQLite and your framework:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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')))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e7ffb4b4.d8e071f0.js b/assets/js/e7ffb4b4.789e1741.js similarity index 97% rename from assets/js/e7ffb4b4.d8e071f0.js rename to assets/js/e7ffb4b4.789e1741.js index f9e0f74ae..42eaf0b75 100644 --- a/assets/js/e7ffb4b4.d8e071f0.js +++ b/assets/js/e7ffb4b4.789e1741.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2119],{7009:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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=[],g={toc:l},c="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},g,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/3.0/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/3.0/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/3.0/universal_service_providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/3.0/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2119],{7009:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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=[],g={toc:l},c="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},g,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/3.0/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/3.0/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/3.0/universal_service_providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/3.0/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e806c7bf.fca6fc61.js b/assets/js/e806c7bf.6fd79788.js similarity index 99% rename from assets/js/e806c7bf.fca6fc61.js rename to assets/js/e806c7bf.6fd79788.js index cfb0aaedc..e79484224 100644 --- a/assets/js/e806c7bf.fca6fc61.js +++ b/assets/js/e806c7bf.6fd79788.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4324],{55195:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>l,default:()=>d,frontMatter:()=>r,metadata:()=>o,toc:()=>s});var n=t(58168),i=(t(96540),t(15680));t(67443);const r={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},l=void 0,o={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},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},{value:"Export the schema from the CLI",id:"export-the-schema-from-the-cli",level:2}],u={toc:s},g="wrapper";function d(e){let{components:a,...t}=e;return(0,i.yg)(g,(0,n.A)({},u,t,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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,i.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,i.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,i.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,i.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Validate]")," attribute to use Laravel validation rules in your\ninput types."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Validate]")," attribute in any query / mutation / field / factory / decorator."),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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 }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password"\n }\n }\n ]\n}\n')),(0,i.yg)("p",null,"You can use any validation rule described in ",(0,i.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,i.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,i.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,i.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Notice that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,i.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,i.yg)("li",{parentName:"ul"},"you MUST add a ",(0,i.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,i.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,i.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,i.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,i.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,i.yg)("p",null,"Note: if you are using ",(0,i.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,i.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,i.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,i.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,i.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,i.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute on each getter."),(0,i.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[MagicField]")," attribute to help you\nworking with magic properties."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,i.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute on the ",(0,i.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,i.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,i.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,i.yg)("p",null,"In short:"),(0,i.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n\n #[Field]\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,i.yg)("div",{class:"alert alert--success"},"This works:",(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[MagicField(name: "phone", phpType:"App\\\\Phone")]\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))),(0,i.yg)("h2",{id:"export-the-schema-from-the-cli"},"Export the schema from the CLI"),(0,i.yg)("p",null,"The extension comes with a special command: ",(0,i.yg)("inlineCode",{parentName:"p"},"graphqlite:export-schema"),"."),(0,i.yg)("p",null,"Usage:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ ./artisan graphqlite:export-schema --output=schema.graphql\n")),(0,i.yg)("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)."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4324],{55195:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>l,default:()=>d,frontMatter:()=>r,metadata:()=>o,toc:()=>s});var n=t(58168),i=(t(96540),t(15680));t(67443);const r={id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features"},l=void 0,o={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},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},{value:"Export the schema from the CLI",id:"export-the-schema-from-the-cli",level:2}],u={toc:s},g="wrapper";function d(e){let{components:a,...t}=e;return(0,i.yg)(g,(0,n.A)({},u,t,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("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,i.yg)("a",{href:"https://github.com/thecodingmachine/graphqlite-laravel"},"Github repository"),"."),(0,i.yg)("p",null,"The Laravel package comes with a number of features to ease the integration of GraphQLite in Laravel."),(0,i.yg)("h2",{id:"support-for-laravel-validation-rules"},"Support for Laravel validation rules"),(0,i.yg)("p",null,"The GraphQLite Laravel package comes with a special ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Validate]")," attribute to use Laravel validation rules in your\ninput types."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Validate]")," attribute in any query / mutation / field / factory / decorator."),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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 }\n },\n {\n "message": "The password must be greater than or equal 8 characters.",\n "extensions": {\n "argument": "password"\n }\n }\n ]\n}\n')),(0,i.yg)("p",null,"You can use any validation rule described in ",(0,i.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/validation#available-validation-rules"},"the Laravel documentation")),(0,i.yg)("h2",{id:"support-for-pagination"},"Support for pagination"),(0,i.yg)("p",null,"In your query, if you explicitly return an object that extends the ",(0,i.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\LengthAwarePaginator"),' class,\nthe query result will be wrapped in a "paginator" type.'),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Notice that:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,i.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")," or a class extending ",(0,i.yg)("inlineCode",{parentName:"li"},"Illuminate\\Pagination\\LengthAwarePaginator")),(0,i.yg)("li",{parentName:"ul"},"you MUST add a ",(0,i.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,i.yg)("p",null,"Once this is done, you can get plenty of useful information about this page:"),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("div",{class:"alert alert--warning"},"Be sure to type hint on the class (",(0,i.yg)("code",null,"Illuminate\\Pagination\\LengthAwarePaginator"),") and not on the interface (",(0,i.yg)("code",null,"Illuminate\\Contracts\\Pagination\\LengthAwarePaginator"),"). The interface itself is not iterable (it does not extend ",(0,i.yg)("code",null,"Traversable"),") and therefore, GraphQLite will refuse to iterate over it."),(0,i.yg)("h3",{id:"simple-paginator"},"Simple paginator"),(0,i.yg)("p",null,"Note: if you are using ",(0,i.yg)("inlineCode",{parentName:"p"},"simplePaginate")," instead of ",(0,i.yg)("inlineCode",{parentName:"p"},"paginate"),", you can type hint on the ",(0,i.yg)("inlineCode",{parentName:"p"},"Illuminate\\Pagination\\Paginator")," class."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"The behaviour will be exactly the same except you will be missing the ",(0,i.yg)("inlineCode",{parentName:"p"},"totalCount")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"lastPage")," fields."),(0,i.yg)("h2",{id:"using-graphqlite-with-eloquent-efficiently"},"Using GraphQLite with Eloquent efficiently"),(0,i.yg)("p",null,"In GraphQLite, you are supposed to put a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute on each getter."),(0,i.yg)("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.yg)("p",null,"So we need to find a workaround. GraphQLite comes with a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[MagicField]")," attribute to help you\nworking with magic properties."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("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.yg)("h3",{id:"pitfalls-to-avoid-with-eloquent"},"Pitfalls to avoid with Eloquent"),(0,i.yg)("p",null,"When designing relationships in Eloquent, you write a method to expose that relationship this way:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"It would be tempting to put a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Field]")," attribute on the ",(0,i.yg)("inlineCode",{parentName:"p"},"phone()")," method, but this will not work. Indeed,\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"phone()")," method does not return a ",(0,i.yg)("inlineCode",{parentName:"p"},"App\\Phone")," object. It is the ",(0,i.yg)("inlineCode",{parentName:"p"},"phone")," magic property that returns it."),(0,i.yg)("p",null,"In short:"),(0,i.yg)("div",{class:"alert alert--danger"},"This does not work:",(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"class User extends Model\n{\n\n #[Field]\n public function phone()\n {\n return $this->hasOne('App\\Phone');\n }\n}\n"))),(0,i.yg)("div",{class:"alert alert--success"},"This works:",(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[MagicField(name: "phone", phpType:"App\\\\Phone")]\nclass User extends Model\n{\n public function phone()\n {\n return $this->hasOne(\'App\\Phone\');\n }\n}\n'))),(0,i.yg)("h2",{id:"export-the-schema-from-the-cli"},"Export the schema from the CLI"),(0,i.yg)("p",null,"The extension comes with a special command: ",(0,i.yg)("inlineCode",{parentName:"p"},"graphqlite:export-schema"),"."),(0,i.yg)("p",null,"Usage:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ ./artisan graphqlite:export-schema --output=schema.graphql\n")),(0,i.yg)("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)."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e8a97ac3.86c008fb.js b/assets/js/e8a97ac3.0a231a8d.js similarity index 99% rename from assets/js/e8a97ac3.86c008fb.js rename to assets/js/e8a97ac3.0a231a8d.js index 335704b0f..e05944685 100644 --- a/assets/js/e8a97ac3.86c008fb.js +++ b/assets/js/e8a97ac3.0a231a8d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4124],{54112:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>l,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(58168),t=(a(96540),a(15680));a(67443);const i={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},o=void 0,s={unversionedId:"other-frameworks",id:"version-8.0.0/other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/other-frameworks.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},l={},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:"Disabling autoloading",id:"disabling-autoloading",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,...a}=e;return(0,t.yg)(d,(0,r.A)({},c,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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->addNamespace('App');\n\n$schema = $factory->createSchema();\n")),(0,t.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the #[Logged] attributes).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the #[Right] attributes).\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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h3",{id:"disabling-autoloading"},"Disabling autoloading"),(0,t.yg)("p",null,"GraphQLite uses ",(0,t.yg)("inlineCode",{parentName:"p"},"kcs/class-finder")," to find all classes that have GraphQLite attributes. By default, it uses\nautoloading under the hood. But if you have an older codebase that contains classes with incorrect or missing\nnamespaces, you may need to use ",(0,t.yg)("inlineCode",{parentName:"p"},"include_once")," instead. To do so, you can overwrite the finder using ",(0,t.yg)("inlineCode",{parentName:"p"},"setFinder()"),":"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use Kcs\\ClassFinder\\Finder\\ComposerFinder;\nuse TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n$factory = new SchemaFactory($cache, $container);\n$factory->addNamespace('App')\n ->setFinder(\n (new ComposerFinder())->useAutoloading(false)\n );\n\n$schema = $factory->createSchema();\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"addNamespace('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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.laminas.dev/laminas-stratigility/"},"Laminas Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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 "laminas/laminas-diactoros": "^2",\n "laminas/laminas-stratigility": "^3",\n "laminas/laminas-httphandlerrunner": "^2",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Laminas ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Laminas Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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 // Any PSR-16 cache should work - APCu is recommended for good\n // performance, but it requires that module to be enabled. For\n // small scale testing with zero dependencies, FilesystemCache\n // can be used instead.\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->addNamespace('App');\n return $factory->createSchema();\n }\n]);\n")),(0,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4124],{54112:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>l,contentTitle:()=>o,default:()=>u,frontMatter:()=>i,metadata:()=>s,toc:()=>p});var r=a(58168),t=(a(96540),a(15680));a(67443);const i={id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework"},o=void 0,s={unversionedId:"other-frameworks",id:"version-8.0.0/other-frameworks",title:"Getting started with any framework",description:"Installation",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/other-frameworks.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},l={},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:"Disabling autoloading",id:"disabling-autoloading",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,...a}=e;return(0,t.yg)(d,(0,r.A)({},c,a,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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,t.yg)("a",{parentName:"p",href:"#psr-15-middleware"},"PSR-15 middleware"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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->addNamespace('App');\n\n$schema = $factory->createSchema();\n")),(0,t.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},'// Configure an authentication service (to resolve the #[Logged] attributes).\n$factory->setAuthenticationService(new VoidAuthenticationService());\n// Configure an authorization service (to resolve the #[Right] attributes).\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,t.yg)("h3",{id:"graphqlite-context"},"GraphQLite context"),(0,t.yg)("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,t.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Context\\Context")," class."),(0,t.yg)("p",null,"For instance:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Context\\Context;\n\n$result = GraphQL::executeQuery($schema, $query, null, new Context(), $variableValues);\n")),(0,t.yg)("h3",{id:"disabling-autoloading"},"Disabling autoloading"),(0,t.yg)("p",null,"GraphQLite uses ",(0,t.yg)("inlineCode",{parentName:"p"},"kcs/class-finder")," to find all classes that have GraphQLite attributes. By default, it uses\nautoloading under the hood. But if you have an older codebase that contains classes with incorrect or missing\nnamespaces, you may need to use ",(0,t.yg)("inlineCode",{parentName:"p"},"include_once")," instead. To do so, you can overwrite the finder using ",(0,t.yg)("inlineCode",{parentName:"p"},"setFinder()"),":"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"use Kcs\\ClassFinder\\Finder\\ComposerFinder;\nuse TheCodingMachine\\GraphQLite\\SchemaFactory;\n\n$factory = new SchemaFactory($cache, $container);\n$factory->addNamespace('App')\n ->setFinder(\n (new ComposerFinder())->useAutoloading(false)\n );\n\n$schema = $factory->createSchema();\n")),(0,t.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"addNamespace('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,t.yg)("h2",{id:"psr-15-middleware"},"PSR-15 Middleware"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("inlineCode",{parentName:"p"},"webonyx/graphql-php")," library."),(0,t.yg)("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,t.yg)("p",null,"In order to get an instance of this middleware, you can use the ",(0,t.yg)("inlineCode",{parentName:"p"},"Psr15GraphQLMiddlewareBuilder")," builder class:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"The builder offers a number of setters to modify its behaviour:"),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("h3",{id:"example"},"Example"),(0,t.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.laminas.dev/laminas-stratigility/"},"Laminas Stratigility")," as a PSR-15 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("pre",null,(0,t.yg)("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 "laminas/laminas-diactoros": "^2",\n "laminas/laminas-stratigility": "^3",\n "laminas/laminas-httphandlerrunner": "^2",\n "mouf/picotainer": "^1.1",\n "symfony/cache": "^4.2"\n },\n "minimum-stability": "dev",\n "prefer-stable": true\n}\n')),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"Here we are initializing a Laminas ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Laminas Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("pre",null,(0,t.yg)("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 // Any PSR-16 cache should work - APCu is recommended for good\n // performance, but it requires that module to be enabled. For\n // small scale testing with zero dependencies, FilesystemCache\n // can be used instead.\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->addNamespace('App');\n return $factory->createSchema();\n }\n]);\n")),(0,t.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)("pre",null,(0,t.yg)("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,t.yg)("pre",null,(0,t.yg)("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,t.yg)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e91daeb9.fbc54514.js b/assets/js/e91daeb9.8e7131fe.js similarity index 99% rename from assets/js/e91daeb9.fbc54514.js rename to assets/js/e91daeb9.8e7131fe.js index aacea6eb7..2ba094b4f 100644 --- a/assets/js/e91daeb9.fbc54514.js +++ b/assets/js/e91daeb9.8e7131fe.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3359],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>N});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),i=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.W6)(),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.aZ)(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 h(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]=g({queryString:a,groupId:n}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(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),h(e)}),[u,h,l]),tabValues:l}}var f=a(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(y,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function N(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},50815:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>u});var n=a(58168),r=(a(96540),a(15680));a(67443),a(11470),a(19365);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/6.1/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/pagination.mdx",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"docs",previous:{title:"File uploads",permalink:"/docs/6.1/file-uploads"},next:{title:"Custom types",permalink:"/docs/6.1/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.yg)(p,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"You will need to install the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"In your query, simply return a class that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.yg)("p",null,'The "count" field returns the ',(0,r.yg)("strong",{parentName:"p"},"total count")," of items."))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3359],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>N});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),i=a(56347),s=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(e){let{queryString:t=!1,groupId:a}=e;const n=(0,i.W6)(),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.aZ)(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 h(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]=g({queryString:a,groupId:n}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(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),h(e)}),[u,h,l]),tabValues:l}}var f=a(92303);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function y(e){let{className:t,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",b.tabItem,o?.className,{"tabs__item--active":i===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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",b.tabList)},r.createElement(y,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function N(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},50815:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>u});var n=a(58168),r=(a(96540),a(15680));a(67443),a(11470),a(19365);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/6.1/pagination",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/pagination.mdx",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"pagination",title:"Paginating large result sets",sidebar_label:"Pagination"},sidebar:"docs",previous:{title:"File uploads",permalink:"/docs/6.1/file-uploads"},next:{title:"Custom types",permalink:"/docs/6.1/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.yg)(p,(0,n.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"You will need to install the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"In your query, simply return a class that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.yg)("p",null,'The "count" field returns the ',(0,r.yg)("strong",{parentName:"p"},"total count")," of items."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/eaa287f0.70bd8003.js b/assets/js/eaa287f0.534b794e.js similarity index 99% rename from assets/js/eaa287f0.70bd8003.js rename to assets/js/eaa287f0.534b794e.js index a7be86069..20f1f37a0 100644 --- a/assets/js/eaa287f0.70bd8003.js +++ b/assets/js/eaa287f0.534b794e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1133],{28571:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>d,contentTitle:()=>r,default:()=>u,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var t=n(58168),i=(n(96540),n(15680));n(67443);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/6.1/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/CHANGELOG.md",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/6.1/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}],g={toc:p},s="wrapper";function u(e){let{components:a,...n}=e;return(0,i.yg)(s,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"610"},"6.1.0"),(0,i.yg)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Drop support for php 7.4")),(0,i.yg)("h2",{id:"500"},"5.0.0"),(0,i.yg)("h4",{id:"dependencies"},"Dependencies:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.yg)("h2",{id:"430"},"4.3.0"),(0,i.yg)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The method ",(0,i.yg)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.yg)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.yg)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.yg)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h4",{id:"new-features"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/input-types#input-attribute"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h4",{id:"breaking-change-3"},"Breaking change:"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h4",{id:"new-features-1"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h4",{id:"new-features-2"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.yg)("p",null,"New framework specific features:"),(0,i.yg)("h4",{id:"symfony"},"Symfony:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h4",{id:"laravel"},"Laravel:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h4",{id:"internals"},"Internals:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1133],{28571:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>d,contentTitle:()=>r,default:()=>u,frontMatter:()=>l,metadata:()=>o,toc:()=>p});var t=n(58168),i=(n(96540),n(15680));n(67443);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/6.1/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.1/CHANGELOG.md",tags:[],version:"6.1",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/6.1/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}],g={toc:p},s="wrapper";function u(e){let{components:a,...n}=e;return(0,i.yg)(s,(0,t.A)({},g,n,{components:a,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"610"},"6.1.0"),(0,i.yg)("h4",{id:"breaking-change"},"Breaking change:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Drop support for php 7.4")),(0,i.yg)("h2",{id:"500"},"5.0.0"),(0,i.yg)("h4",{id:"dependencies"},"Dependencies:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Upgraded to using version 14.9 of ",(0,i.yg)("a",{parentName:"li",href:"https://github.com/webonyx/graphql-php"},"webonyx/graphql-php"))),(0,i.yg)("h2",{id:"430"},"4.3.0"),(0,i.yg)("h4",{id:"breaking-change-1"},"Breaking change:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The method ",(0,i.yg)("inlineCode",{parentName:"li"},"setAnnotationCacheDir($directory)")," has been removed from the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),". The annotation\ncache will use your ",(0,i.yg)("inlineCode",{parentName:"li"},"Psr\\SimpleCache\\CacheInterface")," compliant cache handler set through the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory"),"\nconstructor.")),(0,i.yg)("h4",{id:"minor-changes"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Removed dependency for doctrine/cache and unified some of the cache layers following a PSR interface."),(0,i.yg)("li",{parentName:"ul"},"Cleaned up some of the documentation in an attempt to get things accurate with versioned releases.")),(0,i.yg)("h2",{id:"420"},"4.2.0"),(0,i.yg)("h4",{id:"breaking-change-2"},"Breaking change:"),(0,i.yg)("p",null,"The method signature for ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLOutputType")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"toGraphQLInputType")," have been changed to the following:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h4",{id:"new-features"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/annotations-reference#input-annotation"},"@Input")," annotation is introduced as an alternative to ",(0,i.yg)("inlineCode",{parentName:"li"},"@Factory"),". Now GraphQL input type can be created in the same manner as ",(0,i.yg)("inlineCode",{parentName:"li"},"@Type")," in combination with ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field")," - ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/input-types#input-attribute"},"example"),"."),(0,i.yg)("li",{parentName:"ul"},"New attributes has been added to ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/annotations-reference#field-annotation"},"@Field")," annotation: ",(0,i.yg)("inlineCode",{parentName:"li"},"for"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"inputType")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"description"),"."),(0,i.yg)("li",{parentName:"ul"},"The following annotations now can be applied to class properties directly: ",(0,i.yg)("inlineCode",{parentName:"li"},"@Field"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Logged"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@Right"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@FailWith"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"@HideIfUnauthorized")," and ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security"),".")),(0,i.yg)("h2",{id:"410"},"4.1.0"),(0,i.yg)("h4",{id:"breaking-change-3"},"Breaking change:"),(0,i.yg)("p",null,"There is one breaking change introduced in the minor version (this was important to allow PHP 8 compatibility)."),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"li"},"composer.json"),".")),(0,i.yg)("h4",{id:"new-features-1"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"All annotations can now be accessed as PHP 8 attributes"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"@deprecated")," annotation in your PHP code translates into deprecated fields in your GraphQL schema"),(0,i.yg)("li",{parentName:"ul"},"You can now specify the GraphQL name of the Enum types you define"),(0,i.yg)("li",{parentName:"ul"},"Added the possibility to inject pure Webonyx objects in GraphQLite schema")),(0,i.yg)("h4",{id:"minor-changes-1"},"Minor changes:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from ",(0,i.yg)("inlineCode",{parentName:"li"},"zend/diactoros")," to ",(0,i.yg)("inlineCode",{parentName:"li"},"laminas/diactoros")),(0,i.yg)("li",{parentName:"ul"},"Making the annotation cache directory configurable")),(0,i.yg)("h4",{id:"miscellaneous"},"Miscellaneous:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Migrated from Travis to Github actions")),(0,i.yg)("h2",{id:"400"},"4.0.0"),(0,i.yg)("p",null,"This is a complete refactoring from 3.x. While existing annotations are kept compatible, the internals have completely\nchanged."),(0,i.yg)("h4",{id:"new-features-2"},"New features:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"You can directly ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/inheritance-interfaces#mapping-interfaces"},"annotate a PHP interface with ",(0,i.yg)("inlineCode",{parentName:"a"},"@Type")," to make it a GraphQL interface")),(0,i.yg)("li",{parentName:"ul"},"You can autowire services in resolvers, thanks to the new ",(0,i.yg)("inlineCode",{parentName:"li"},"@Autowire")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/validation"},"user input validation")," (using the Symfony Validator or the Laravel validator or a custom ",(0,i.yg)("inlineCode",{parentName:"li"},"@Assertion")," annotation"),(0,i.yg)("li",{parentName:"ul"},"Improved security handling:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Unauthorized access to fields can now generate GraphQL errors (rather that schema errors in GraphQLite v3)"),(0,i.yg)("li",{parentName:"ul"},"Added fine-grained security using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@Security")," annotation. A field can now be ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.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.yg)("inlineCode",{parentName:"li"},"BlogPost")," only for post that the current user wrote."),(0,i.yg)("li",{parentName:"ul"},"You can now inject the current logged user in any query / mutation / field using the ",(0,i.yg)("inlineCode",{parentName:"li"},"@InjectUser")," annotation"))),(0,i.yg)("li",{parentName:"ul"},"Performance:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can inject the ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/query-plan"},"Webonyx query plan in a parameter from a resolver")),(0,i.yg)("li",{parentName:"ul"},"You can use the ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/prefetch-method"},'dataloader pattern to improve performance drastically via the "prefetchMethod" attribute')))),(0,i.yg)("li",{parentName:"ul"},"Customizable error handling has been added:",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"You can throw ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/error-handling#many-errors-for-one-exception"},"many errors in one exception")," with ",(0,i.yg)("inlineCode",{parentName:"li"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLAggregateException")))),(0,i.yg)("li",{parentName:"ul"},"You can force input types using ",(0,i.yg)("inlineCode",{parentName:"li"},'@UseInputType(for="$id", inputType="ID!")')),(0,i.yg)("li",{parentName:"ul"},"You can extend an input types (just like you could extend an output type in v3) using ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/extend-input-type"},"the new ",(0,i.yg)("inlineCode",{parentName:"a"},"@Decorate")," annotation")),(0,i.yg)("li",{parentName:"ul"},"In a factory, you can ",(0,i.yg)("a",{parentName:"li",href:"input-types#ignoring-some-parameters"},"exclude some optional parameters from the GraphQL schema"))),(0,i.yg)("p",null,"Many extension points have been added"),(0,i.yg)("ul",null,(0,i.yg)("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.yg)("li",{parentName:"ul"},"Added ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/field-middlewares"},'"field middlewares"')," (useful to add middleware that modify the way GraphQL fields are handled)"),(0,i.yg)("li",{parentName:"ul"},"Added a ",(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/argument-resolving"},'"parameter type mapper"')," (useful to add customize parameter resolution or add custom annotations related to parameters)")),(0,i.yg)("p",null,"New framework specific features:"),(0,i.yg)("h4",{id:"symfony"},"Symfony:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},'The Symfony bundle now provides a "login" and a "logout" mutation (and also a "me" query)')),(0,i.yg)("h4",{id:"laravel"},"Laravel:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/laravel-package-advanced#support-for-pagination"},"Native integration with the Laravel paginator")," has been added")),(0,i.yg)("h4",{id:"internals"},"Internals:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," class has been split in many different services (",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder"),", ",(0,i.yg)("inlineCode",{parentName:"li"},"TypeHandler"),", and a\nchain of ",(0,i.yg)("em",{parentName:"li"},"root type mappers"),")"),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," class has been completely removed."),(0,i.yg)("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!")))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/eb333c39.554c4783.js b/assets/js/eb333c39.d433d098.js similarity index 98% rename from assets/js/eb333c39.554c4783.js rename to assets/js/eb333c39.d433d098.js index 2cca3a287..0b36c54e3 100644 --- a/assets/js/eb333c39.554c4783.js +++ b/assets/js/eb333c39.d433d098.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5738],{99752:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>i,default:()=>g,frontMatter:()=>a,metadata:()=>s,toc:()=>p});var r=t(58168),o=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,o.yg)(h,(0,r.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,o.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,o.yg)("p",null,"By default, when you throw a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,o.yg)("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.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,o.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,o.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,o.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,o.yg)("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.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,o.yg)("p",null,"will generate:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,o.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,o.yg)("p",null,"will generate:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,o.yg)("p",null,"Rather that throwing the base ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,o.yg)("p",null,"Any exception that implements interface ",(0,o.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,o.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,o.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,o.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,o.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,o.yg)("p",null,"Actually, the ",(0,o.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,o.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,o.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,o.yg)("p",null,"If an exception that does not implement ",(0,o.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,o.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,o.yg)("p",null,"You can ",(0,o.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.0/symfony-bundle"},"Symfony"),", ",(0,o.yg)("a",{parentName:"p",href:"/docs/4.0/laravel-package"},"Laravel"),")."),(0,o.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5738],{99752:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>i,default:()=>g,frontMatter:()=>a,metadata:()=>s,toc:()=>p});var r=t(58168),o=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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 g(e){let{components:n,...t}=e;return(0,o.yg)(h,(0,r.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,o.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,o.yg)("p",null,"By default, when you throw a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,o.yg)("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.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,o.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,o.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,o.yg)("h2",{id:"customizing-the-category"},"Customizing the category"),(0,o.yg)("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.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},'throw new GraphQLException("Not found", 404, null, "NOT_FOUND");\n')),(0,o.yg)("p",null,"will generate:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,o.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,o.yg)("p",null,"will generate:"),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,o.yg)("p",null,"Rather that throwing the base ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,o.yg)("p",null,"Any exception that implements interface ",(0,o.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,o.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,o.yg)("pre",null,(0,o.yg)("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.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,o.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,o.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,o.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,o.yg)("p",null,"Actually, the ",(0,o.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,o.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,o.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,o.yg)("p",null,"If an exception that does not implement ",(0,o.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,o.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,o.yg)("p",null,"You can ",(0,o.yg)("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.yg)("a",{parentName:"p",href:"/docs/4.0/symfony-bundle"},"Symfony"),", ",(0,o.yg)("a",{parentName:"p",href:"/docs/4.0/laravel-package"},"Laravel"),")."),(0,o.yg)("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).'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/eca0cf35.fa28893f.js b/assets/js/eca0cf35.511fc0e7.js similarity index 99% rename from assets/js/eca0cf35.fa28893f.js rename to assets/js/eca0cf35.511fc0e7.js index 74f2f6e50..eae23bc69 100644 --- a/assets/js/eca0cf35.fa28893f.js +++ b/assets/js/eca0cf35.511fc0e7.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1039],{4084:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>r,metadata:()=>l,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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:n,...t}=e;return(0,i.yg)(c,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,i.yg)("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.yg)("a",{href:"inheritance"},"Inheritance")," section"),(0,i.yg)("p",null,"Let's assume you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,i.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Using ",(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Let's break this sample:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")),(0,i.yg)("p",null,"With the ",(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,i.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,i.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,i.yg)("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.yg)("p",null,'Using the "',(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,i.yg)("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([[1039],{4084:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>o,default:()=>u,frontMatter:()=>r,metadata:()=>l,toc:()=>p});var a=t(58168),i=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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:n,...t}=e;return(0,i.yg)(c,(0,a.A)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"Fields exposed in a GraphQL type do not need to be all part of the same class."),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation to add additional fields to a type that is already declared."),(0,i.yg)("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.yg)("a",{href:"inheritance"},"Inheritance")," section"),(0,i.yg)("p",null,"Let's assume you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," class. In order to get the name of a product, there is no ",(0,i.yg)("inlineCode",{parentName:"p"},"getName()")," method in\nthe product because the name needs to be translated in the correct language. You have a ",(0,i.yg)("inlineCode",{parentName:"p"},"TranslationService")," to do that."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Using ",(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType"),", you can add an additional ",(0,i.yg)("inlineCode",{parentName:"p"},"name")," field to your product:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"Let's break this sample:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @ExtendType(class=Product::class)\n */\n")),(0,i.yg)("p",null,"With the ",(0,i.yg)("inlineCode",{parentName:"p"},"@ExtendType")," annotation, we tell GraphQLite that we want to add fields in the GraphQL type mapped to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"Product")," PHP class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class must be in the types namespace. You configured this namespace when you installed GraphQLite."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"ProductType")," class is actually a ",(0,i.yg)("strong",{parentName:"li"},"service"),". You can therefore inject dependencies in it (like the ",(0,i.yg)("inlineCode",{parentName:"li"},"$translationService")," in this example)")),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field"),' annotation is used to add the "name" field to the ',(0,i.yg)("inlineCode",{parentName:"p"},"Product")," type."),(0,i.yg)("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.yg)("p",null,'Using the "',(0,i.yg)("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.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-graphql"},"Extend type Product {\n name(language: !String): String!\n}\n")),(0,i.yg)("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.85adf6e2.js b/assets/js/ece9cf29.e7a221c7.js similarity index 99% rename from assets/js/ece9cf29.85adf6e2.js rename to assets/js/ece9cf29.e7a221c7.js index ef99e2ec5..1429207eb 100644 --- a/assets/js/ece9cf29.85adf6e2.js +++ b/assets/js/ece9cf29.e7a221c7.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6981],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),s=a(56347),i=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),h(e)}),[u,h,l]),tabValues:l}}var f=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},g=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},o,{className:(0,l.A)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":s===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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},61548:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(g,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"You will need to install the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"In your query, simply return a class that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.yg)("p",null,'The "count" field returns the ',(0,r.yg)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6981],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),s=a(56347),i=a(57485),u=a(31682),c=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 g(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.W6)(),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.aZ)(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 h(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(!g({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}),[p,h]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=i??p;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&s(f)}),[f]);return{selectedValue:o,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),u(e),h(e)}),[u,h,l]),tabValues:l}}var f=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,o.a_)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=u[a].value;n!==s&&(p(t),i(n))},g=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.A)("tabs",{"tabs--block":a},t)},u.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>c.push(e),onKeyDown:g,onClick:d},o,{className:(0,l.A)("tabs__item",y.tabItem,o?.className,{"tabs__item--active":s===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 w(e){const t=h(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,f.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},61548:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>m,frontMatter:()=>s,metadata:()=>u,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function m(e){let{components:t,...a}=e;return(0,r.yg)(g,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"It is quite common to have to paginate over large result sets."),(0,r.yg)("p",null,"GraphQLite offers a simple way to do that using ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas"),"."),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://thecodingmachine.github.io/tdbm/doc/limit_offset_resultset.html"},"TDBM"),"."),(0,r.yg)("div",{class:"alert alert--warning"},"If you are a Laravel user, Eloquent does not come with a Porpaginas iterator. However, ",(0,r.yg)("a",{href:"laravel-package-advanced"},"the GraphQLite Laravel bundle comes with its own pagination system"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"You will need to install the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/beberlei/porpaginas"},"Porpaginas")," library to benefit from this feature."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require beberlei/porpaginas\n")),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"In your query, simply return a class that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"Porpaginas\\Result"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Notice that:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"the method return type MUST BE ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")," or a class implementing ",(0,r.yg)("inlineCode",{parentName:"li"},"Porpaginas\\Result")),(0,r.yg)("li",{parentName:"ul"},"you MUST add a ",(0,r.yg)("inlineCode",{parentName:"li"},"@return")," statement to help GraphQLite find the type of the list")),(0,r.yg)("p",null,"Once this is done, you can paginate directly from your GraphQL query:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"products {\n items(limit: 10, offset: 20) {\n id\n name\n }\n count\n}\n")),(0,r.yg)("p",null,'Results are wrapped into an item field. You can use the "limit" and "offset" parameters to apply pagination automatically.'),(0,r.yg)("p",null,'The "count" field returns the ',(0,r.yg)("strong",{parentName:"p"},"total count")," of items."))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/ed0c0463.324ec300.js b/assets/js/ed0c0463.6293e55c.js similarity index 99% rename from assets/js/ed0c0463.324ec300.js rename to assets/js/ed0c0463.6293e55c.js index fa80214fa..09578502a 100644 --- a/assets/js/ed0c0463.324ec300.js +++ b/assets/js/ed0c0463.6293e55c.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8950],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),u=a(56347),i=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),g=(()=>{const e=i??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&u(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}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var g=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},8438:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},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.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.yg)("p",null,"You must start by installing this package:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.yg)("p",null,"In order to use this, you must first be sure that the ",(0,r.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.yg)("pre",null,(0,r.yg)("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([[8950],{19365:(e,t,a)=>{a.d(t,{A:()=>o});var n=a(96540),r=a(20053);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.A)(l.tabItem,o),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>I});var n=a(58168),r=a(96540),l=a(20053),o=a(23104),u=a(56347),i=a(57485),s=a(31682),p=a(89466);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.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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.W6)(),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.aZ)(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.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),g=(()=>{const e=i??c;return m({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{g&&u(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}`);u(e),s(e),f(e)}),[s,f,l]),tabValues:l}}var g=a(92303);const y={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:u,selectValue:i,tabValues:s}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,o.a_)(),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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:o}=e;return r.createElement("li",(0,n.A)({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.A)("tabs__item",y.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 w(e){const t=f(e);return r.createElement("div",{className:(0,l.A)("tabs-container",y.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function I(e){const t=(0,g.A)();return r.createElement(w,(0,n.A)({key:String(t)},e))}},8438:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>i,default:()=>h,frontMatter:()=>u,metadata:()=>s,toc:()=>c});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),o=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},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.yg)(m,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/jaydenseric/graphql-multipart-request-spec"},"multipart requests"),"."),(0,r.yg)("h2",{id:"installation"},"Installation"),(0,r.yg)("p",null,"GraphQLite supports this extension through the use of the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"Ecodev/graphql-upload")," library."),(0,r.yg)("p",null,"You must start by installing this package:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,r.yg)("h3",{id:"if-you-are-using-the-symfony-bundle"},"If you are using the Symfony bundle"),(0,r.yg)("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.yg)("h3",{id:"if-you-are-using-a-psr-15-compatible-framework"},"If you are using a PSR-15 compatible framework"),(0,r.yg)("p",null,"In order to use this, you must first be sure that the ",(0,r.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," PSR-15 middleware is part of your middleware pipe."),(0,r.yg)("p",null,"Simply add ",(0,r.yg)("inlineCode",{parentName:"p"},"GraphQL\\Upload\\UploadMiddleware")," to your middleware pipe."),(0,r.yg)("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.yg)("p",null,"Please check the Ecodev/graphql-upload library ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/Ecodev/graphql-upload"},"documentation"),"\nfor more information on how to integrate it in your framework."),(0,r.yg)("h2",{id:"usage"},"Usage"),(0,r.yg)("p",null,"To handle an uploaded file, you type-hint against the PSR-7 ",(0,r.yg)("inlineCode",{parentName:"p"},"UploadedFileInterface"),":"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Of course, you need to use a GraphQL client that is compatible with multipart requests. See ",(0,r.yg)("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.yg)("p",null,"The GraphQL client must send the file using the Upload type."),(0,r.yg)("pre",null,(0,r.yg)("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.882f2590.js b/assets/js/eec7caa6.1619fe9d.js similarity index 99% rename from assets/js/eec7caa6.882f2590.js rename to assets/js/eec7caa6.1619fe9d.js index b4b2fcb31..db4cb86c0 100644 --- a/assets/js/eec7caa6.882f2590.js +++ b/assets/js/eec7caa6.1619fe9d.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5282],{8384:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>g,frontMatter:()=>r,metadata:()=>s,toc:()=>l});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},o=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",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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},u={},l=[{value:"#[Logged] and #[Right] attributes",id:"logged-and-right-attributes",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 / subscriptions",id:"hiding-fields--queries--mutations--subscriptions",level:2}],d={toc:l},h="wrapper";function g(e){let{components:t,...n}=e;return(0,i.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some\nqueries/mutations/subscriptions or fields reserved to some users."),(0,i.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to\nresources:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,i.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"#[Logged]")," attribute")," (restrict access to logged users)"),(0,i.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,i.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"#[Right]")," attribute")," (restrict access to logged users with certain rights)."),(0,i.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/fine-grained-security"},(0,i.yg)("inlineCode",{parentName:"a"},"#[Security]")," attribute")," (restrict access for some given resources to some users).")),(0,i.yg)("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.yg)("br",null),"See ",(0,i.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,i.yg)("h2",{id:"logged-and-right-attributes"},(0,i.yg)("inlineCode",{parentName:"h2"},"#[Logged]")," and ",(0,i.yg)("inlineCode",{parentName:"h2"},"#[Right]")," attributes"),(0,i.yg)("p",null,"GraphQLite exposes two attributes (",(0,i.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Right]"),") that you can use to restrict access to a resource."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"In the example above, the query ",(0,i.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,i.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,i.yg)("p",null,(0,i.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes can be used next to:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"#[Query]")," attributes"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"#[Mutation]")," attributes"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," attributes")),(0,i.yg)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/subscription/field, an error is raised and the query fails."),(0,i.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,i.yg)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation/subscription\nthey have no access to, you can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," attribute."),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," attribute contains the value that will be returned for users with insufficient rights."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[InjectUser]")," attribute to get an instance of the current user logged in."),(0,i.yg)("pre",null,(0,i.yg)("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 * @return Product\n */\n #[Query]\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n")),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[InjectUser]")," attribute can be used next to:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"#[Query]")," attributes"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"#[Mutation]")," attributes"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," attributes")),(0,i.yg)("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.yg)("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,i.yg)("inlineCode",{parentName:"p"},"#[Logged]")," attribute."),(0,i.yg)("h2",{id:"hiding-fields--queries--mutations--subscriptions"},"Hiding fields / queries / mutations / subscriptions"),(0,i.yg)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/subscriptions/types available.\nSome will be available to him and some won't."),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"#[HideIfUnauthorized]")," attribute. Beware of ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/annotations-reference"},"it's limitations"),"."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optional from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5282],{8384:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>g,frontMatter:()=>r,metadata:()=>s,toc:()=>l});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},o=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",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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},u={},l=[{value:"#[Logged] and #[Right] attributes",id:"logged-and-right-attributes",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 / subscriptions",id:"hiding-fields--queries--mutations--subscriptions",level:2}],d={toc:l},h="wrapper";function g(e){let{components:t,...n}=e;return(0,i.yg)(h,(0,a.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"You might not want to expose your GraphQL API to anyone. Or you might want to keep some\nqueries/mutations/subscriptions or fields reserved to some users."),(0,i.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to\nresources:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,i.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"#[Logged]")," attribute")," (restrict access to logged users)"),(0,i.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,i.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"#[Right]")," attribute")," (restrict access to logged users with certain rights)."),(0,i.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,i.yg)("a",{parentName:"li",href:"/docs/next/fine-grained-security"},(0,i.yg)("inlineCode",{parentName:"a"},"#[Security]")," attribute")," (restrict access for some given resources to some users).")),(0,i.yg)("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.yg)("br",null),"See ",(0,i.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,i.yg)("h2",{id:"logged-and-right-attributes"},(0,i.yg)("inlineCode",{parentName:"h2"},"#[Logged]")," and ",(0,i.yg)("inlineCode",{parentName:"h2"},"#[Right]")," attributes"),(0,i.yg)("p",null,"GraphQLite exposes two attributes (",(0,i.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Right]"),") that you can use to restrict access to a resource."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"In the example above, the query ",(0,i.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,i.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,i.yg)("p",null,(0,i.yg)("inlineCode",{parentName:"p"},"#[Logged]")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Right]")," attributes can be used next to:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"#[Query]")," attributes"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"#[Mutation]")," attributes"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," attributes")),(0,i.yg)("div",{class:"alert alert--info"},"By default, if a user tries to access an unauthorized query/mutation/subscription/field, an error is raised and the query fails."),(0,i.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,i.yg)("p",null,"If you do not want an error to be thrown when a user attempts to query a field/query/mutation/subscription\nthey have no access to, you can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," attribute."),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[FailWith]")," attribute contains the value that will be returned for users with insufficient rights."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[InjectUser]")," attribute to get an instance of the current user logged in."),(0,i.yg)("pre",null,(0,i.yg)("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 * @return Product\n */\n #[Query]\n public function product(\n int $id,\n #[InjectUser]\n User $user\n ): Product\n {\n // ...\n }\n}\n")),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"#[InjectUser]")," attribute can be used next to:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"#[Query]")," attributes"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"#[Mutation]")," attributes"),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," attributes")),(0,i.yg)("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.yg)("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,i.yg)("inlineCode",{parentName:"p"},"#[Logged]")," attribute."),(0,i.yg)("h2",{id:"hiding-fields--queries--mutations--subscriptions"},"Hiding fields / queries / mutations / subscriptions"),(0,i.yg)("p",null,"By default, a user analysing the GraphQL schema can see all queries/mutations/subscriptions/types available.\nSome will be available to him and some won't."),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"#[HideIfUnauthorized]")," attribute. Beware of ",(0,i.yg)("a",{parentName:"p",href:"/docs/next/annotations-reference"},"it's limitations"),"."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optional from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f07f4757.206f1033.js b/assets/js/f07f4757.56c56ba2.js similarity index 99% rename from assets/js/f07f4757.206f1033.js rename to assets/js/f07f4757.56c56ba2.js index bb94d41c5..1bfde1213 100644 --- a/assets/js/f07f4757.206f1033.js +++ b/assets/js/f07f4757.56c56ba2.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7341],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var t=a(96540),r=a(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),l=a(20053),i=a(23104),s=a(56347),p=a(57485),c=a(31682),o=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function m(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function g(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function y(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!g({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[p,c]=d({queryString:a,groupId:t}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=p??u;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{h&&s(h)}),[h]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),y(e)}),[c,y,l]),tabValues:l}}var h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=c[a].value;t!==s&&(u(n),p(t))},g=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:g,onClick:m},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function N(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(v,(0,t.A)({},e,n)))}function T(e){const n=(0,h.A)();return r.createElement(N,(0,t.A)({key:String(n)},e))}},74810:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>d,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var t=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:n,...a}=e;return(0,r.yg)(g,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.yg)("p",null,"Written in ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.yg)("p",null,"The GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.yg)("p",null,"This will translate in GraphQL schema as:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.yg)("p",null,"Please note that you do not need to put the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.yg)("p",null,"You don't have to explicitly put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}d.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7341],{19365:(e,n,a)=>{a.d(n,{A:()=>i});var t=a(96540),r=a(20053);const l={tabItem:"tabItem_Ymn6"};function i(e){let{children:n,hidden:a,className:i}=e;return t.createElement("div",{role:"tabpanel",className:(0,r.A)(l.tabItem,i),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>T});var t=a(58168),r=a(96540),l=a(20053),i=a(23104),s=a(56347),p=a(57485),c=a(31682),o=a(89466);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:a,attributes:t,default:r}}=e;return{value:n,label:a,attributes:t,default:r}}))}function m(e){const{values:n,children:a}=e;return(0,r.useMemo)((()=>{const e=n??u(a);return function(e){const n=(0,c.X)(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,a])}function g(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,p.aZ)(l),(0,r.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function y(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!g({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[p,c]=d({queryString:a,groupId:t}),[u,y]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=p??u;return g({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{h&&s(h)}),[h]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!g({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),y(e)}),[c,y,l]),tabValues:l}}var h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:p,tabValues:c}=e;const o=[],{blockElementScrollPositionUntilNextRender:u}=(0,i.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=c[a].value;t!==s&&(u(n),p(t))},g=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},c.map((e=>{let{value:n,label:a,attributes:i}=e;return r.createElement("li",(0,t.A)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:g,onClick:m},i,{className:(0,l.A)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function N(e){const n=y(e);return r.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},r.createElement(b,(0,t.A)({},e,n)),r.createElement(v,(0,t.A)({},e,n)))}function T(e){const n=(0,h.A)();return r.createElement(N,(0,t.A)({key:String(n)},e))}},74810:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>p,default:()=>d,frontMatter:()=>s,metadata:()=>c,toc:()=>u});var t=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:n,...a}=e;return(0,r.yg)(g,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("h2",{id:"modeling-inheritance"},"Modeling inheritance"),(0,r.yg)("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.yg)("p",null,"Let's say you have two classes, ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," (which extends ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact"),"):"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Now, let's assume you have a query that returns a contact:"),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"class ContactController\n{\n #[Query]\n public function getContact(): Contact\n {\n // ...\n }\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"When writing your GraphQL query, you are able to use fragments to retrieve fields from the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"contact {\n name\n ... User {\n email\n }\n}\n")),(0,r.yg)("p",null,"Written in ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),", the representation of types\nwould look like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Behind the scene, GraphQLite will detect that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," class is extended by the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class.\nBecause the class is extended, a GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface")," interface is created dynamically."),(0,r.yg)("p",null,"The GraphQL ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," type will also automatically implement this ",(0,r.yg)("inlineCode",{parentName:"p"},"ContactInterface"),". The interface contains all the fields\navailable in the ",(0,r.yg)("inlineCode",{parentName:"p"},"Contact")," type."),(0,r.yg)("h2",{id:"mapping-interfaces"},"Mapping interfaces"),(0,r.yg)("p",null,"If you want to create a pure GraphQL interface, you can also add a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on a PHP interface."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\ninterface UserInterface\n{\n #[Field]\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This will automatically create a GraphQL interface whose description is:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n")),(0,r.yg)("h3",{id:"implementing-interfaces"},"Implementing interfaces"),(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Type]\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n"))),(0,r.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Type\n */\nclass User implements UserInterface\n{\n public function getUserName(): string;\n}\n")))),(0,r.yg)("p",null,"This will translate in GraphQL schema as:"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype User implements UserInterface {\n userName: String!\n}\n")),(0,r.yg)("p",null,"Please note that you do not need to put the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation again in the implementing class."),(0,r.yg)("h3",{id:"interfaces-without-an-explicit-implementing-type"},"Interfaces without an explicit implementing type"),(0,r.yg)("p",null,"You don't have to explicitly put a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation on the class implementing the interface (though this\nis usually a good idea)."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("p",null,"In the example above, because the ",(0,r.yg)("inlineCode",{parentName:"p"},"User")," class has no ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotations, GraphQLite will\ncreate a ",(0,r.yg)("inlineCode",{parentName:"p"},"UserImpl")," type that implements ",(0,r.yg)("inlineCode",{parentName:"p"},"UserInterface"),"."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"interface UserInterface {\n userName: String!\n}\n\ntype UserImpl implements UserInterface {\n userName: String!\n}\n")))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f2710c27.7e389950.js b/assets/js/f2710c27.94ebd814.js similarity index 99% rename from assets/js/f2710c27.7e389950.js rename to assets/js/f2710c27.94ebd814.js index 7d438e5b1..679744b82 100644 --- a/assets/js/f2710c27.7e389950.js +++ b/assets/js/f2710c27.94ebd814.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[321],{97460:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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:g},d="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(d,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/next/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[SourceField]")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[SourceField]")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"#[MagicField]")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/next/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[321],{97460:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>r,default:()=>u,frontMatter:()=>o,metadata:()=>l,toc:()=>g});var n=a(58168),i=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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={},g=[{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:g},d="wrapper";function u(e){let{components:t,...a}=e;return(0,i.yg)(d,(0,n.A)({},p,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("h2",{id:"migrating-from-v40-to-v41"},"Migrating from v4.0 to v4.1"),(0,i.yg)("p",null,"GraphQLite follows Semantic Versioning. GraphQLite 4.1 is backward compatible with GraphQLite 4.0. See\n",(0,i.yg)("a",{parentName:"p",href:"/docs/next/semver"},"semantic versioning")," for more details."),(0,i.yg)("p",null,"There is one exception though: the ",(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"ecodev/graphql-upload")," to your ",(0,i.yg)("inlineCode",{parentName:"p"},"composer.json")," by running this command:"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require ecodev/graphql-upload\n")),(0,i.yg)("h2",{id:"migrating-from-v30-to-v40"},"Migrating from v3.0 to v4.0"),(0,i.yg)("p",null,'If you are a "regular" GraphQLite user, migration to v4 should be straightforward:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Annotations are mostly untouched. The only annotation that is changed is the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[SourceField]")," annotation.",(0,i.yg)("ul",{parentName:"li"},(0,i.yg)("li",{parentName:"ul"},"Check your code for every places where you use the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[SourceField]")," annotation:"),(0,i.yg)("li",{parentName:"ul"},'The "id" attribute has been remove (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(id=true)"),"). Instead, use ",(0,i.yg)("inlineCode",{parentName:"li"},'@SourceField(outputType="ID")')),(0,i.yg)("li",{parentName:"ul"},'The "logged", "right" and "failWith" attributes have been removed (',(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(logged=true)"),").\nInstead, use the annotations attribute with the same annotations you use for the ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," annotation:\n",(0,i.yg)("inlineCode",{parentName:"li"},"@SourceField(annotations={@Logged, @FailWith(null)})")),(0,i.yg)("li",{parentName:"ul"},"If you use magic property and were creating a getter for every magic property (to put a ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Field]")," annotation on it),\nyou can now replace this getter with a ",(0,i.yg)("inlineCode",{parentName:"li"},"#[MagicField]")," annotation."))),(0,i.yg)("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.yg)("a",{parentName:"li",href:"/docs/next/annotations-reference#hideifunauthorized-annotation"},(0,i.yg)("inlineCode",{parentName:"a"},"@HideIfUnauthorized")," annotation")),(0,i.yg)("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.yg)("li",{parentName:"ul"},"If you are relying on the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," to bootstrap GraphQLite, you have nothing to do.")),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory"),') or if you implemented custom "TypeMappers", you will need to adapt your code:'),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilderFactory")," is gone. Directly instantiate ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," in v4."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"CompositeTypeMapper")," class has no more constructor arguments. Use the ",(0,i.yg)("inlineCode",{parentName:"li"},"addTypeMapper")," method to register\ntype mappers in it."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"FieldsBuilder")," now accept an extra argument: the ",(0,i.yg)("inlineCode",{parentName:"li"},"RootTypeMapper")," that you need to instantiate accordingly. Take\na look at the ",(0,i.yg)("inlineCode",{parentName:"li"},"SchemaFactory")," class for an example of proper configuration."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"ResolvableMutableInputInterface")," (an input object type that contains its own resolver)")),(0,i.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaManager")," instead."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f309eabc.17fc6e9e.js b/assets/js/f309eabc.81e87848.js similarity index 99% rename from assets/js/f309eabc.17fc6e9e.js rename to assets/js/f309eabc.81e87848.js index 47948d6d0..1ccdb3895 100644 --- a/assets/js/f309eabc.17fc6e9e.js +++ b/assets/js/f309eabc.81e87848.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[324],{31928:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>i,default:()=>d,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var r=t(58168),o=(t(96540),t(15680));t(67443);const a={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},i=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},p={},l=[{value:"HTTP response code",id:"http-response-code",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:l},h="wrapper";function d(e){let{components:n,...t}=e;return(0,o.yg)(h,(0,r.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,o.yg)("pre",null,(0,o.yg)("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 }\n ]\n}\n')),(0,o.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,o.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,o.yg)("p",null,"By default, when you throw a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,o.yg)("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.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,o.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,o.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,o.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,o.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,o.yg)("p",null,"will generate:"),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "field": "name"\n }\n }\n ]\n}\n')),(0,o.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,o.yg)("p",null,"Rather that throwing the base ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,o.yg)("p",null,"Any exception that implements interface ",(0,o.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,o.yg)("pre",null,(0,o.yg)("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 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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,o.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,o.yg)("pre",null,(0,o.yg)("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,o.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,o.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,o.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,o.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,o.yg)("p",null,"Actually, the ",(0,o.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,o.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,o.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,o.yg)("p",null,"If an exception that does not implement ",(0,o.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,o.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,o.yg)("p",null,"You can ",(0,o.yg)("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.yg)("a",{parentName:"p",href:"/docs/next/symfony-bundle"},"Symfony"),", ",(0,o.yg)("a",{parentName:"p",href:"/docs/next/laravel-package"},"Laravel"),")."),(0,o.yg)("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([[324],{31928:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>i,default:()=>d,frontMatter:()=>a,metadata:()=>s,toc:()=>l});var r=t(58168),o=(t(96540),t(15680));t(67443);const a={id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},i=void 0,s={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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},p={},l=[{value:"HTTP response code",id:"http-response-code",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:l},h="wrapper";function d(e){let{components:n,...t}=e;return(0,o.yg)(h,(0,r.A)({},c,t,{components:n,mdxType:"MDXLayout"}),(0,o.yg)("p",null,'In GraphQL, when an error occurs, the server must add an "error" entry in the response.'),(0,o.yg)("pre",null,(0,o.yg)("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 }\n ]\n}\n')),(0,o.yg)("p",null,"You can generate such errors with GraphQLite by throwing a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),"."),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},'use TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLException;\n\nthrow new GraphQLException("Exception message");\n')),(0,o.yg)("h2",{id:"http-response-code"},"HTTP response code"),(0,o.yg)("p",null,"By default, when you throw a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", the HTTP status code will be 500."),(0,o.yg)("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.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},'// This exception will generate a HTTP 404 status code\nthrow new GraphQLException("Not found", 404);\n')),(0,o.yg)("div",{class:"alert alert--info"},"GraphQL allows to have several errors for one request. If you have several",(0,o.yg)("code",null,"GraphQLException")," thrown for the same request, the HTTP status code used will be the highest one."),(0,o.yg)("h2",{id:"customizing-the-extensions-section"},"Customizing the extensions section"),(0,o.yg)("p",null,'You can customize the whole "extensions" section with the 5th parameter of the constructor:'),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-php"},"throw new GraphQLException(\"Field required\", 400, null, \"VALIDATION\", ['field' => 'name']);\n")),(0,o.yg)("p",null,"will generate:"),(0,o.yg)("pre",null,(0,o.yg)("code",{parentName:"pre",className:"language-json"},'{\n "errors": [\n {\n "message": "Field required",\n "extensions": {\n "field": "name"\n }\n }\n ]\n}\n')),(0,o.yg)("h2",{id:"writing-your-own-exceptions"},"Writing your own exceptions"),(0,o.yg)("p",null,"Rather that throwing the base ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLException"),", you should consider writing your own exception."),(0,o.yg)("p",null,"Any exception that implements interface ",(0,o.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface"),' will be displayed\nin the GraphQL "errors" section.'),(0,o.yg)("pre",null,(0,o.yg)("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 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.yg)("h2",{id:"many-errors-for-one-exception"},"Many errors for one exception"),(0,o.yg)("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.yg)("p",null,"If you want to display several exceptions, you can bundle these exceptions in a ",(0,o.yg)("inlineCode",{parentName:"p"},"GraphQLAggregateException")," that you can\nthrow."),(0,o.yg)("pre",null,(0,o.yg)("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,o.yg)("h2",{id:"webonyx-exceptions"},"Webonyx exceptions"),(0,o.yg)("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.yg)("inlineCode",{parentName:"p"},"GraphQL\\Error\\Error")," exception or any exception implementing\n",(0,o.yg)("a",{parentName:"p",href:"http://webonyx.github.io/graphql-php/error-handling/#errors-in-graphql"},(0,o.yg)("inlineCode",{parentName:"a"},"GraphQL\\Error\\ClientAware")," interface")),(0,o.yg)("p",null,"Actually, the ",(0,o.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Exceptions\\GraphQLExceptionInterface")," extends Webonyx's ",(0,o.yg)("inlineCode",{parentName:"p"},"ClientAware")," interface."),(0,o.yg)("h2",{id:"behaviour-of-exceptions-that-do-not-implement-clientaware"},"Behaviour of exceptions that do not implement ClientAware"),(0,o.yg)("p",null,"If an exception that does not implement ",(0,o.yg)("inlineCode",{parentName:"p"},"ClientAware")," is thrown, by default, GraphQLite will not catch it."),(0,o.yg)("p",null,"The exception will propagate to your framework error handler/middleware that is in charge of displaying the classical error page."),(0,o.yg)("p",null,"You can ",(0,o.yg)("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.yg)("a",{parentName:"p",href:"/docs/next/symfony-bundle"},"Symfony"),", ",(0,o.yg)("a",{parentName:"p",href:"/docs/next/laravel-package"},"Laravel"),")."),(0,o.yg)("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/f48e2589.563b4cd6.js b/assets/js/f48e2589.fe03d88b.js similarity index 97% rename from assets/js/f48e2589.563b4cd6.js rename to assets/js/f48e2589.fe03d88b.js index a7f96e3a2..dc9731f0c 100644 --- a/assets/js/f48e2589.563b4cd6.js +++ b/assets/js/f48e2589.fe03d88b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4690],{90329:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"docs",previous:{title:"GraphQLite",permalink:"/docs/6.1/"},next:{title:"Symfony bundle",permalink:"/docs/6.1/symfony-bundle"}},d={},l=[],c={toc:l},g="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,r.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4690],{90329:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>l});var r=a(58168),i=(a(96540),a(15680));a(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"docs",previous:{title:"GraphQLite",permalink:"/docs/6.1/"},next:{title:"Symfony bundle",permalink:"/docs/6.1/symfony-bundle"}},d={},l=[],c={toc:l},g="wrapper";function p(e){let{components:t,...a}=e;return(0,i.yg)(g,(0,r.A)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("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.yg)("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.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/symfony-bundle"},"Get started with Symfony")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/laravel-package"},"Get started with Laravel")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/universal-service-providers"},"Get started with a framework compatible with container-interop/service-provider")),(0,i.yg)("li",{parentName:"ul"},(0,i.yg)("a",{parentName:"li",href:"/docs/6.1/other-frameworks"},"Get started with another framework (or no framework)"))))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f4e1d1ba.0c7d42fe.js b/assets/js/f4e1d1ba.8b13eb66.js similarity index 99% rename from assets/js/f4e1d1ba.0c7d42fe.js rename to assets/js/f4e1d1ba.8b13eb66.js index a2056ce5c..c0051d236 100644 --- a/assets/js/f4e1d1ba.0c7d42fe.js +++ b/assets/js/f4e1d1ba.8b13eb66.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2421],{18942:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(58168),a=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:t(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,n,t)=>{t.d(n,{A:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2421],{18942:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>r,default:()=>c,frontMatter:()=>l,metadata:()=>o,toc:()=>s});var i=t(58168),a=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(p,(0,i.A)({},u,l,{components:n,mdxType:"MDXLayout"}),(0,a.yg)("small",null,"Available in GraphQLite 4.0+"),(0,a.yg)("p",null,"Just like the ",(0,a.yg)("inlineCode",{parentName:"p"},"@Logged")," or ",(0,a.yg)("inlineCode",{parentName:"p"},"@Right")," annotation, you can develop your own annotation that extends/modifies the behaviour of a field/query/mutation."),(0,a.yg)("div",{class:"alert alert--warning"},"If you want to create an annotation that targets a single argument (like ",(0,a.yg)("code",null,'@AutoWire(for="$service")'),"), you should rather check the documentation about ",(0,a.yg)("a",{href:"argument-resolving"},"custom argument resolving")),(0,a.yg)("h2",{id:"field-middlewares"},"Field middlewares"),(0,a.yg)("p",null,"GraphQLite is based on the Webonyx/Graphql-PHP library. In Webonyx, fields are represented by the ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition")," class.\nIn order to create a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),' instance for your field, GraphQLite goes through a series of "middlewares".'),(0,a.yg)("p",null,(0,a.yg)("img",{src:t(8643).A,width:"960",height:"540"})),(0,a.yg)("p",null,"Each middleware is passed a ",(0,a.yg)("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.yg)("p",null,"Each middleware must return a ",(0,a.yg)("inlineCode",{parentName:"p"},"GraphQL\\Type\\Definition\\FieldDefinition")," (the object representing a field in Webonyx/GraphQL-PHP)."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The role of a middleware is to analyze the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor")," and modify it (or to directly return a ",(0,a.yg)("inlineCode",{parentName:"p"},"FieldDefinition"),")."),(0,a.yg)("p",null,"If you want the field to purely disappear, your middleware can return ",(0,a.yg)("inlineCode",{parentName:"p"},"null"),"."),(0,a.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,a.yg)("p",null,"Take a look at the ",(0,a.yg)("inlineCode",{parentName:"p"},"QueryFieldDescriptor::getMiddlewareAnnotations()"),"."),(0,a.yg)("p",null,"It returns the list of annotations applied to your field that implements the ",(0,a.yg)("inlineCode",{parentName:"p"},"MiddlewareAnnotationInterface"),"."),(0,a.yg)("p",null,"Let's imagine you want to add a ",(0,a.yg)("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.yg)("p",null,"First, we have to define the annotation. Annotations are handled by the great ",(0,a.yg)("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.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"Apart from being a classical annotation/attribute, this class implements the ",(0,a.yg)("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.yg)("p",null,"Now, we can write a middleware that will act upon this annotation."),(0,a.yg)("pre",null,(0,a.yg)("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.yg)("p",null,"The final thing we have to do is to register the middleware."),(0,a.yg)("ul",null,(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"Assuming you are using the ",(0,a.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," to initialize GraphQLite, you can register the field middleware using:"),(0,a.yg)("pre",{parentName:"li"},(0,a.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addFieldMiddleware(new OnlyDebugFieldMiddleware());\n"))),(0,a.yg)("li",{parentName:"ul"},(0,a.yg)("p",{parentName:"li"},"If you are using the Symfony bundle, you can register your field middleware services by tagging them with the ",(0,a.yg)("inlineCode",{parentName:"p"},"graphql.field_middleware")," tag."))))}c.isMDXComponent=!0},8643:(e,n,t)=>{t.d(n,{A:()=>i});const i=t.p+"assets/images/field_middleware-5c3e3b4da480c49d048d527f93cc970d.svg"}}]); \ No newline at end of file diff --git a/assets/js/f5b0a435.d957599d.js b/assets/js/f5b0a435.e9c309d4.js similarity index 99% rename from assets/js/f5b0a435.d957599d.js rename to assets/js/f5b0a435.e9c309d4.js index 1de08639a..1374bf1c2 100644 --- a/assets/js/f5b0a435.d957599d.js +++ b/assets/js/f5b0a435.e9c309d4.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7373],{19365:(e,n,a)=>{a.d(n,{A:()=>r});var t=a(96540),p=a(20053);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:a,className:r}=e;return t.createElement("div",{role:"tabpanel",className:(0,p.A)(l.tabItem,r),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>N});var t=a(58168),p=a(96540),l=a(20053),r=a(23104),i=a(56347),s=a(57485),u=a(31682),o=a(89466);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:a,attributes:t,default:p}}=e;return{value:n,label:a,attributes:t,default:p}}))}function m(e){const{values:n,children:a}=e;return(0,p.useMemo)((()=>{const e=n??c(a);return function(e){const n=(0,u.X)(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,a])}function y(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:a}=e;const t=(0,i.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function g(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[r,i]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!y({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[s,u]=d({queryString:a,groupId:t}),[c,g]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,p.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=s??c;return y({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{h&&i(h)}),[h]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!y({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 h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=u[a].value;t!==i&&(c(n),s(t))},y=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},u.map((e=>{let{value:n,label:a,attributes:r}=e;return p.createElement("li",(0,t.A)({role:"tab",tabIndex:i===n?0:-1,"aria-selected":i===n,key:n,ref:e=>o.push(e),onKeyDown:y,onClick:m},r,{className:(0,l.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":i===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function T(e){const n=g(e);return p.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},p.createElement(b,(0,t.A)({},e,n)),p.createElement(v,(0,t.A)({},e,n)))}function N(e){const n=(0,h.A)();return p.createElement(T,(0,t.A)({key:String(n)},e))}},8710:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var t=a(58168),p=(a(96540),a(15680)),l=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.1/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.1/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"You can create a GraphQL union type ",(0,p.yg)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.yg)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.yg)("p",null,"You will first need to install ",(0,p.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("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.yg)("em",null,"type mappers")," in the ",(0,p.yg)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.yg)("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.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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([[7373],{19365:(e,n,a)=>{a.d(n,{A:()=>r});var t=a(96540),p=a(20053);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:a,className:r}=e;return t.createElement("div",{role:"tabpanel",className:(0,p.A)(l.tabItem,r),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>N});var t=a(58168),p=a(96540),l=a(20053),r=a(23104),i=a(56347),s=a(57485),u=a(31682),o=a(89466);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:a,attributes:t,default:p}}=e;return{value:n,label:a,attributes:t,default:p}}))}function m(e){const{values:n,children:a}=e;return(0,p.useMemo)((()=>{const e=n??c(a);return function(e){const n=(0,u.X)(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,a])}function y(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:a}=e;const t=(0,i.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,s.aZ)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function g(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[r,i]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!y({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[s,u]=d({queryString:a,groupId:t}),[c,g]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,p.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=s??c;return y({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{h&&i(h)}),[h]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!y({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 h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:i,selectValue:s,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=u[a].value;t!==i&&(c(n),s(t))},y=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},u.map((e=>{let{value:n,label:a,attributes:r}=e;return p.createElement("li",(0,t.A)({role:"tab",tabIndex:i===n?0:-1,"aria-selected":i===n,key:n,ref:e=>o.push(e),onKeyDown:y,onClick:m},r,{className:(0,l.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":i===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function T(e){const n=g(e);return p.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},p.createElement(b,(0,t.A)({},e,n)),p.createElement(v,(0,t.A)({},e,n)))}function N(e){const n=(0,h.A)();return p.createElement(T,(0,t.A)({key:String(n)},e))}},8710:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>s,default:()=>d,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var t=a(58168),p=(a(96540),a(15680)),l=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.1/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.1/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"You can create a GraphQL union type ",(0,p.yg)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.yg)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.yg)("p",null,"You will first need to install ",(0,p.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("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.yg)("em",null,"type mappers")," in the ",(0,p.yg)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.yg)("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.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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/f7c03581.64966720.js b/assets/js/f7c03581.ab9ca9fa.js similarity index 99% rename from assets/js/f7c03581.64966720.js rename to assets/js/f7c03581.ab9ca9fa.js index 8e30a531a..3f9a692f3 100644 --- a/assets/js/f7c03581.64966720.js +++ b/assets/js/f7c03581.ab9ca9fa.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[770],{42775:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>r,default:()=>p,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var a=t(58168),i=(t(96540),t(15680));t(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.1/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/6.1/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},g="wrapper";function p(e){let{components:n,...t}=e;return(0,i.yg)(g,(0,a.A)({},u,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"If the ",(0,i.yg)("a",{parentName:"p",href:"/docs/6.1/authentication-authorization#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.yg)("p",null,"Using the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,i.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,i.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,i.yg)("li",{parentName:"ul"},"...")),(0,i.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,i.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,i.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,i.yg)("code",null,"@Security")," annotation and Symfony's ",(0,i.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,i.yg)("h2",{id:"the-is_granted-function"},"The ",(0,i.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n")),(0,i.yg)("p",null,"is similar to"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n')),(0,i.yg)("p",null,"In addition, the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, the ",(0,i.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,i.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,i.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,i.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,i.yg)("a",{parentName:"p",href:"/docs/6.1/authentication-authorization#not-throwing-errors"},(0,i.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.yg)("p",null,"You cannot use the ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,i.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n')),(0,i.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,i.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n")),(0,i.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,i.yg)("p",null,"If you are using Laravel, you will ",(0,i.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,i.yg)("p",null,"If you are using another framework, you need to know that the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,i.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,i.yg)("a",{parentName:"p",href:"/docs/6.1/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[770],{42775:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>r,default:()=>p,frontMatter:()=>o,metadata:()=>s,toc:()=>c});var a=t(58168),i=(t(96540),t(15680));t(67443);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/6.1/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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.1/authentication-authorization"},next:{title:"Connecting security to your framework",permalink:"/docs/6.1/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},g="wrapper";function p(e){let{components:n,...t}=e;return(0,i.yg)(g,(0,a.A)({},u,t,{components:n,mdxType:"MDXLayout"}),(0,i.yg)("p",null,"If the ",(0,i.yg)("a",{parentName:"p",href:"/docs/6.1/authentication-authorization#logged-and-right-annotations"},(0,i.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,i.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.yg)("p",null,"Using the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,i.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,i.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,i.yg)("li",{parentName:"ul"},"...")),(0,i.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,i.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,i.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,i.yg)("code",null,"@Security")," annotation and Symfony's ",(0,i.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,i.yg)("h2",{id:"the-is_granted-function"},"The ",(0,i.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n")),(0,i.yg)("p",null,"is similar to"),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n')),(0,i.yg)("p",null,"In addition, the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, the ",(0,i.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,i.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,i.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,i.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,i.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,i.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,i.yg)("a",{parentName:"p",href:"/docs/6.1/authentication-authorization#not-throwing-errors"},(0,i.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,i.yg)("p",null,"You cannot use the ",(0,i.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,i.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,i.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,i.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n')),(0,i.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,i.yg)("p",null,"You can use the ",(0,i.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,i.yg)("pre",null,(0,i.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,i.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,i.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,i.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,i.yg)("p",null,"The ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,i.yg)("pre",null,(0,i.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n")),(0,i.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,i.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,i.yg)("p",null,"If you are using Laravel, you will ",(0,i.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,i.yg)("p",null,"If you are using another framework, you need to know that the ",(0,i.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,i.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,i.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,i.yg)("a",{parentName:"p",href:"/docs/6.1/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f9063551.7d8ac123.js b/assets/js/f9063551.630b68d3.js similarity index 99% rename from assets/js/f9063551.7d8ac123.js rename to assets/js/f9063551.630b68d3.js index b8bee8d62..05b27a314 100644 --- a/assets/js/f9063551.7d8ac123.js +++ b/assets/js/f9063551.630b68d3.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8868],{85249:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},m,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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([[8868],{85249:(e,a,n)=>{n.r(a),n.d(a,{assets:()=>s,contentTitle:()=>o,default:()=>d,frontMatter:()=>i,metadata:()=>l,toc:()=>p});var t=n(58168),r=(n(96540),n(15680));n(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},g="wrapper";function d(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},m,n,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("p",null,"Using a ",(0,r.yg)("strong",{parentName:"p"},"parameter middleware"),", you can hook into the argument resolution of field/query/mutation/factory."),(0,r.yg)("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.yg)("p",null,"As an example, GraphQLite uses ",(0,r.yg)("em",{parentName:"p"},"parameter middlewares")," internally to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject the Webonyx GraphQL resolution object when you type-hint on the ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," object. For instance:"),(0,r.yg)("pre",{parentName:"li"},(0,r.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @return Product[]\n */\n#[Query]\npublic function products(ResolveInfo $info): array\n")),(0,r.yg)("p",{parentName:"li"},"In the query above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"$info")," argument is filled with the Webonyx ",(0,r.yg)("inlineCode",{parentName:"p"},"ResolveInfo")," class thanks to the\n",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Mappers/Parameters/ResolveInfoParameterHandler.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ResolveInfoParameterHandler parameter middleware")))),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Inject a service from the container when you use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Autowire")," annotation")),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("p",{parentName:"li"},"Perform validation with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Validate")," annotation (in Laravel package)"))),(0,r.yg)("p",null,(0,r.yg)("strong",{parentName:"p"},"Parameter middlewares")),(0,r.yg)("img",{src:"/img/parameter_middleware.svg",width:"70%"}),(0,r.yg)("p",null,"Each middleware is passed number of objects describing the parameter:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"a PHP ",(0,r.yg)("inlineCode",{parentName:"li"},"ReflectionParameter")," object representing the parameter being manipulated"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\DocBlock")," instance (useful to analyze the ",(0,r.yg)("inlineCode",{parentName:"li"},"@param")," comment if any)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"phpDocumentor\\Reflection\\Type")," instance (useful to analyze the type if the argument)"),(0,r.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("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.yg)("li",{parentName:"ul"},"a ",(0,r.yg)("inlineCode",{parentName:"li"},"$next")," handler to pass the argument resolving to the next middleware.")),(0,r.yg)("p",null,"Parameter resolution is done in 2 passes."),(0,r.yg)("p",null,"On the first pass, middlewares are traversed. They must return a ",(0,r.yg)("inlineCode",{parentName:"p"},"TheCodingMachine\\GraphQLite\\Parameters\\ParameterInterface")," (an object that does the actual resolving)."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Then, resolution actually happen by executing the resolver (this is the second pass)."),(0,r.yg)("h2",{id:"annotations-parsing"},"Annotations parsing"),(0,r.yg)("p",null,"If you plan to use annotations while resolving arguments, your annotation should extend the ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite/blob/master/src/Annotations/ParameterAnnotationInterface.php"},(0,r.yg)("inlineCode",{parentName:"a"},"ParameterAnnotationInterface"))),(0,r.yg)("p",null,"For instance, if we want GraphQLite to inject a service in an argument, we can use ",(0,r.yg)("inlineCode",{parentName:"p"},'@Autowire(for="myService")'),"."),(0,r.yg)("p",null,"For PHP 8 attributes, we only need to put declare the annotation can target parameters: ",(0,r.yg)("inlineCode",{parentName:"p"},"#[Attribute(Attribute::TARGET_PARAMETER)]"),"."),(0,r.yg)("p",null,"The annotation looks like this:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"writing-the-parameter-middleware"},"Writing the parameter middleware"),(0,r.yg)("p",null,"The middleware purpose is to analyze a parameter and decide whether or not it can handle it."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The last step is to write the actual parameter resolver."),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"registering-a-parameter-middleware"},"Registering a parameter middleware"),(0,r.yg)("p",null,"The last step is to register the parameter middleware we just wrote:"),(0,r.yg)("p",null,"You can register your own parameter middlewares using the ",(0,r.yg)("inlineCode",{parentName:"p"},"SchemaFactory::addParameterMiddleware()")," method."),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"$schemaFactory->addParameterMiddleware(new ContainerParameterHandler($container));\n")),(0,r.yg)("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/f90c5a21.2c8a41a6.js b/assets/js/f90c5a21.e280e7eb.js similarity index 98% rename from assets/js/f90c5a21.2c8a41a6.js rename to assets/js/f90c5a21.e280e7eb.js index 2c2de8f90..9f314f163 100644 --- a/assets/js/f90c5a21.2c8a41a6.js +++ b/assets/js/f90c5a21.e280e7eb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5830],{89654:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>l,default:()=>y,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={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-8.0.0/extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/extend-input-type.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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"}},p={},d=[],u={toc:d},s="wrapper";function y(e){let{components:t,...n}=e;return(0,i.yg)(s,(0,a.A)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,i.yg)("code",null,"#[Factory]")," tag, ",(0,i.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,i.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,i.yg)("p",null,"Just like with output type (that can be ",(0,i.yg)("a",{parentName:"p",href:"/docs/extend-type"},"extended using the ",(0,i.yg)("inlineCode",{parentName:"a"},"ExtendType")," attribute"),"), you can extend/modify\nan input type using the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Decorate]")," attribute."),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Decorate]")," attribute to add additional fields to an input type that is already declared by a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Factory]")," attribute,\nor to modify the returned object."),(0,i.yg)("div",{class:"alert alert--info"},"The ",(0,i.yg)("code",null,"#[Decorate]")," attribute is very useful in scenarios where you cannot touch the ",(0,i.yg)("code",null,"#[Factory]")," method. This can happen if the ",(0,i.yg)("code",null,"#[Factory]")," method is defined in a third-party library or if the ",(0,i.yg)("code",null,"#[Factory]")," method is part of auto-generated code."),(0,i.yg)("p",null,"Let's assume you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Factory]")," to create the input type."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Assuming you ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,i.yg)("p",null,"A few things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,i.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,i.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Decorate]")," attribute must contain a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"#[Factory]"),' attribute, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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."))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5830],{89654:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>l,default:()=>y,frontMatter:()=>r,metadata:()=>o,toc:()=>d});var a=n(58168),i=(n(96540),n(15680));n(67443);const r={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-8.0.0/extend-input-type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-8.0.0/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-8.0.0/extend-input-type.mdx",tags:[],version:"8.0.0",lastUpdatedBy:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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"}},p={},d=[],u={toc:d},s="wrapper";function y(e){let{components:t,...n}=e;return(0,i.yg)(s,(0,a.A)({},u,n,{components:t,mdxType:"MDXLayout"}),(0,i.yg)("small",null,"Available in GraphQLite 4.0+"),(0,i.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,i.yg)("code",null,"#[Factory]")," tag, ",(0,i.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,i.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,i.yg)("p",null,"Just like with output type (that can be ",(0,i.yg)("a",{parentName:"p",href:"/docs/extend-type"},"extended using the ",(0,i.yg)("inlineCode",{parentName:"a"},"ExtendType")," attribute"),"), you can extend/modify\nan input type using the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Decorate]")," attribute."),(0,i.yg)("p",null,"Use the ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Decorate]")," attribute to add additional fields to an input type that is already declared by a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Factory]")," attribute,\nor to modify the returned object."),(0,i.yg)("div",{class:"alert alert--info"},"The ",(0,i.yg)("code",null,"#[Decorate]")," attribute is very useful in scenarios where you cannot touch the ",(0,i.yg)("code",null,"#[Factory]")," method. This can happen if the ",(0,i.yg)("code",null,"#[Factory]")," method is defined in a third-party library or if the ",(0,i.yg)("code",null,"#[Factory]")," method is part of auto-generated code."),(0,i.yg)("p",null,"Let's assume you have a ",(0,i.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,i.yg)("inlineCode",{parentName:"p"},"#[Factory]")," to create the input type."),(0,i.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,"Assuming you ",(0,i.yg)("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.yg)("pre",null,(0,i.yg)("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,i.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,i.yg)("p",null,"A few things to notice:"),(0,i.yg)("ul",null,(0,i.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,i.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,i.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,i.yg)("li",{parentName:"ul"},"The ",(0,i.yg)("inlineCode",{parentName:"li"},"#[Decorate]")," attribute must contain a ",(0,i.yg)("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.yg)("inlineCode",{parentName:"li"},"#[Factory]"),' attribute, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,i.yg)("div",{class:"alert alert--warning"},(0,i.yg)("strong",null,"Heads up!")," The ",(0,i.yg)("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.yg)("br",null),(0,i.yg)("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."))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f94b062c.e1257188.js b/assets/js/f94b062c.1b4b2049.js similarity index 99% rename from assets/js/f94b062c.e1257188.js rename to assets/js/f94b062c.1b4b2049.js index 4f83cfa17..6d250db47 100644 --- a/assets/js/f94b062c.e1257188.js +++ b/assets/js/f94b062c.1b4b2049.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8933],{19365:(e,a,t)=>{t.d(a,{A:()=>l});var n=t(96540),r=t(20053);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:a,hidden:t,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(o.tabItem,l),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),o=t(20053),l=t(23104),i=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function g(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function d(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,i.W6)(),o=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(o),(0,r.useCallback)((e=>{if(!o)return;const a=new URLSearchParams(n.location.search);a.set(o,e),n.replace({...n.location,search:a.toString()})}),[o,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,o=g(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!d({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:o}))),[s,u]=y({queryString:t,groupId:n}),[c,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,o]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:a,block:t,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.a_)(),g=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==i&&(c(a),s(n))},d=e=>{let a=null;switch(e.key){case"Enter":g(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:l}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:i===a?0:-1,"aria-selected":i===a,key:a,ref:e=>p.push(e),onKeyDown:d,onClick:g},l,{className:(0,o.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":i===a})}),t??a)})))}function v(e){let{lazy:a,children:t,selectedValue:n}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function N(e){const a=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,a)),r.createElement(v,(0,n.A)({},e,a)))}function T(e){const a=(0,m.A)();return r.createElement(N,(0,n.A)({key:String(a)},e))}},93197:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),o=(t(67443),t(11470)),l=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:c},d="wrapper";function y(e){let{components:a,...t}=e;return(0,r.yg)(d,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"If the ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/authentication-authorization#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.yg)("li",{parentName:"ul"},"...")),(0,r.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.yg)("code",null,"@Security")," annotation and Symfony's ",(0,r.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.yg)("h2",{id:"the-is_granted-function"},"The ",(0,r.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.yg)("p",null,"is similar to"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.yg)("p",null,"In addition, the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/authentication-authorization#not-throwing-errors"},(0,r.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"You cannot use the ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.yg)("p",null,"If you are using Laravel, you will ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.yg)("p",null,"If you are using another framework, you need to know that the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}y.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8933],{19365:(e,a,t)=>{t.d(a,{A:()=>l});var n=t(96540),r=t(20053);const o={tabItem:"tabItem_Ymn6"};function l(e){let{children:a,hidden:t,className:l}=e;return n.createElement("div",{role:"tabpanel",className:(0,r.A)(o.tabItem,l),hidden:t},a)}},11470:(e,a,t)=>{t.d(a,{A:()=>T});var n=t(58168),r=t(96540),o=t(20053),l=t(23104),i=t(56347),s=t(57485),u=t(31682),p=t(89466);function c(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:a}=e;return!!a&&"object"==typeof a&&"value"in a}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:a,label:t,attributes:n,default:r}}=e;return{value:a,label:t,attributes:n,default:r}}))}function g(e){const{values:a,children:t}=e;return(0,r.useMemo)((()=>{const e=a??c(t);return function(e){const a=(0,u.X)(e,((e,a)=>e.value===a.value));if(a.length>0)throw new Error(`Docusaurus error: Duplicate values "${a.map((e=>e.value)).join(", ")}" found in . Every value needs to be unique.`)}(e),e}),[a,t])}function d(e){let{value:a,tabValues:t}=e;return t.some((e=>e.value===a))}function y(e){let{queryString:a=!1,groupId:t}=e;const n=(0,i.W6)(),o=function(e){let{queryString:a=!1,groupId:t}=e;if("string"==typeof a)return a;if(!1===a)return null;if(!0===a&&!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:a,groupId:t});return[(0,s.aZ)(o),(0,r.useCallback)((e=>{if(!o)return;const a=new URLSearchParams(n.location.search);a.set(o,e),n.replace({...n.location,search:a.toString()})}),[o,n])]}function h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,o=g(e),[l,i]=(0,r.useState)((()=>function(e){let{defaultValue:a,tabValues:t}=e;if(0===t.length)throw new Error("Docusaurus error: the component requires at least one children component");if(a){if(!d({value:a,tabValues:t}))throw new Error(`Docusaurus error: The has a defaultValue "${a}" 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 a}const n=t.find((e=>e.default))??t[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:a,tabValues:o}))),[s,u]=y({queryString:t,groupId:n}),[c,h]=function(e){let{groupId:a}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(a),[n,o]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&o.set(e)}),[t,o])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(m)}),[m]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);i(e),u(e),h(e)}),[u,h,o]),tabValues:o}}var m=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:a,block:t,selectedValue:i,selectValue:s,tabValues:u}=e;const p=[],{blockElementScrollPositionUntilNextRender:c}=(0,l.a_)(),g=e=>{const a=e.currentTarget,t=p.indexOf(a),n=u[t].value;n!==i&&(c(a),s(n))},d=e=>{let a=null;switch(e.key){case"Enter":g(e);break;case"ArrowRight":{const t=p.indexOf(e.currentTarget)+1;a=p[t]??p[0];break}case"ArrowLeft":{const t=p.indexOf(e.currentTarget)-1;a=p[t]??p[p.length-1];break}}a?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.A)("tabs",{"tabs--block":t},a)},u.map((e=>{let{value:a,label:t,attributes:l}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:i===a?0:-1,"aria-selected":i===a,key:a,ref:e=>p.push(e),onKeyDown:d,onClick:g},l,{className:(0,o.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":i===a})}),t??a)})))}function v(e){let{lazy:a,children:t,selectedValue:n}=e;const o=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){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,a)=>(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n}))))}function N(e){const a=h(e);return r.createElement("div",{className:(0,o.A)("tabs-container",f.tabList)},r.createElement(b,(0,n.A)({},e,a)),r.createElement(v,(0,n.A)({},e,a)))}function T(e){const a=(0,m.A)();return r.createElement(N,(0,n.A)({key:String(a)},e))}},93197:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>s,default:()=>y,frontMatter:()=>i,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),o=(t(67443),t(11470)),l=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],g={toc:c},d="wrapper";function y(e){let{components:a,...t}=e;return(0,r.yg)(d,(0,n.A)({},g,t,{components:a,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"If the ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/authentication-authorization#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotations")," are not\ngranular enough for your needs, you can use the advanced ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"Using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation, you can write an ",(0,r.yg)("em",{parentName:"p"},"expression")," that can contain custom logic. For instance:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"Check that a user can access a given resource"),(0,r.yg)("li",{parentName:"ul"},"Check that a user has one right or another right"),(0,r.yg)("li",{parentName:"ul"},"...")),(0,r.yg)("h2",{id:"using-the-security-annotation"},"Using the @Security annotation"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation is very flexible: it allows you to pass an expression that can contains custom logic:"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("em",{parentName:"p"},"expression")," defined in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation must conform to ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/4.4/components/expression_language/syntax.html"},"Symfony's Expression Language syntax")),(0,r.yg)("div",{class:"alert alert--info"},"If you are a Symfony user, you might already be used to the ",(0,r.yg)("code",null,"@Security")," annotation. Most of the inspiration of this annotation comes from Symfony. Warning though! GraphQLite's ",(0,r.yg)("code",null,"@Security")," annotation and Symfony's ",(0,r.yg)("code",null,"@Security")," annotation are slightly different. Especially, the two annotations do not live in the same namespace!"),(0,r.yg)("h2",{id:"the-is_granted-function"},"The ",(0,r.yg)("inlineCode",{parentName:"h2"},"is_granted")," function"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function to check if a user has a special right."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('ROLE_ADMIN')\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('ROLE_ADMIN')\")\n")))),(0,r.yg)("p",null,"is similar to"),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Right("ROLE_ADMIN")]\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'@Right("ROLE_ADMIN")\n')))),(0,r.yg)("p",null,"In addition, the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted"),' function accepts a second optional parameter: the "scope" of the right.'),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the ",(0,r.yg)("inlineCode",{parentName:"p"},"getPost")," method can be called only if the logged user has the 'POST_SHOW' permission on the\n",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object. You can notice that the ",(0,r.yg)("inlineCode",{parentName:"p"},"$post")," object comes from the parameters."),(0,r.yg)("h2",{id:"accessing-method-parameters"},"Accessing method parameters"),(0,r.yg)("p",null,"All parameters passed to the method can be accessed in the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," expression."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, we tweak a bit the Security annotation purpose to do simple input validation."),(0,r.yg)("h2",{id:"setting-http-code-and-error-message"},"Setting HTTP code and error message"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes to set the HTTP code and GraphQL error message."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("h2",{id:"setting-a-default-value"},"Setting a default value"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"failWith")," attribute\nto set a default value."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute behaves just like the ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/authentication-authorization#not-throwing-errors"},(0,r.yg)("inlineCode",{parentName:"a"},"@FailWith")," annotation"),"\nbut for a given ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation."),(0,r.yg)("p",null,"You cannot use the ",(0,r.yg)("inlineCode",{parentName:"p"},"failWith")," attribute along ",(0,r.yg)("inlineCode",{parentName:"p"},"statusCode")," or ",(0,r.yg)("inlineCode",{parentName:"p"},"message")," attributes."),(0,r.yg)("h2",{id:"accessing-the-user"},"Accessing the user"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"user")," variable to access the currently logged user.\nYou can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_logged()")," function to check if a user is logged or not."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},'#[Query]\n#[Security("is_logged() && user.age > 18")]\npublic function getNSFWImages(): array\n{\n // ...\n}\n'))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"accessing-the-current-object"},"Accessing the current object"),(0,r.yg)("p",null,"You can use the ",(0,r.yg)("inlineCode",{parentName:"p"},"this")," variable to access any (public) property / method of the current class."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"available-scope"},"Available scope"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Security")," annotation can be used in any query, mutation or field, so anywhere you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query"),", ",(0,r.yg)("inlineCode",{parentName:"p"},"@Mutation"),"\nor ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation."),(0,r.yg)("h2",{id:"how-to-restrict-access-to-a-given-resource"},"How to restrict access to a given resource"),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," method can be used to restrict access to a specific resource."),(0,r.yg)(o.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(l.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"#[Security(\"is_granted('POST_SHOW', post)\")]\n"))),(0,r.yg)(l.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-php"},"@Security(\"is_granted('POST_SHOW', post)\")\n")))),(0,r.yg)("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.yg)("p",null,"If you are using Symfony, you will ",(0,r.yg)("a",{parentName:"p",href:"https://symfony.com/doc/current/security/voters.html"},"create a custom voter"),"."),(0,r.yg)("p",null,"If you are using Laravel, you will ",(0,r.yg)("a",{parentName:"p",href:"https://laravel.com/docs/6.x/authorization"},"create a Gate or a Policy"),"."),(0,r.yg)("p",null,"If you are using another framework, you need to know that the ",(0,r.yg)("inlineCode",{parentName:"p"},"is_granted")," function simply forwards the call to\nthe ",(0,r.yg)("inlineCode",{parentName:"p"},"isAllowed")," method of the configured ",(0,r.yg)("inlineCode",{parentName:"p"},"AuthorizationSerice"),". See ",(0,r.yg)("a",{parentName:"p",href:"/docs/5.0/implementing-security"},"Connecting GraphQLite to your framework's security module\n")," for more details"))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f9511b3d.c73b3d9d.js b/assets/js/f9511b3d.12ef6432.js similarity index 99% rename from assets/js/f9511b3d.c73b3d9d.js rename to assets/js/f9511b3d.12ef6432.js index 0fd2b8e84..71e6fc2cd 100644 --- a/assets/js/f9511b3d.c73b3d9d.js +++ b/assets/js/f9511b3d.12ef6432.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7258],{19365:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(96540),r=a(20053);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.A)(l.tabItem,i),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>x});var n=a(58168),r=a(96540),l=a(20053),i=a(23104),o=a(56347),u=a(57485),s=a(31682),c=a(89466);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,s.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 m(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(!y({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}),[p,m]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??p;return y({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),m(e)}),[s,m,l]),tabValues:l}}var f=a(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=s[a].value;n!==o&&(p(t),u(n))},y=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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:y,onClick:d},i,{className:(0,l.A)("tabs__item",g.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 T(e){const t=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",g.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function x(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},91371:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type"}},c={},p=[],d={toc:p},y="wrapper";function h(e){let{components:t,...a}=e;return(0,r.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/3.0/extend_type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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([[7258],{19365:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(96540),r=a(20053);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.A)(l.tabItem,i),hidden:a},t)}},11470:(e,t,a)=>{a.d(t,{A:()=>x});var n=a(58168),r=a(96540),l=a(20053),i=a(23104),o=a(56347),u=a(57485),s=a(31682),c=a(89466);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,s.X)(e,((e,t)=>e.value===t.value));if(t.length>0)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 y(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.W6)(),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.aZ)(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 m(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(!y({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}),[p,m]=function(e){let{groupId:t}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(t),[n,l]=(0,c.Dv)(a);return[n,(0,r.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:n}),f=(()=>{const e=u??p;return y({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{f&&o(f)}),[f]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!y({value:e,tabValues:l}))throw new Error(`Can't select invalid tab value=${e}`);o(e),s(e),m(e)}),[s,m,l]),tabValues:l}}var f=a(92303);const g={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:a,selectedValue:o,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.a_)(),d=e=>{const t=e.currentTarget,a=c.indexOf(t),n=s[a].value;n!==o&&(p(t),u(n))},y=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.A)("tabs",{"tabs--block":a},t)},s.map((e=>{let{value:t,label:a,attributes:i}=e;return r.createElement("li",(0,n.A)({role:"tab",tabIndex:o===t?0:-1,"aria-selected":o===t,key:t,ref:e=>c.push(e),onKeyDown:y,onClick:d},i,{className:(0,l.A)("tabs__item",g.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 T(e){const t=m(e);return r.createElement("div",{className:(0,l.A)("tabs-container",g.tabList)},r.createElement(b,(0,n.A)({},e,t)),r.createElement(v,(0,n.A)({},e,t)))}function x(e){const t=(0,f.A)();return r.createElement(T,(0,n.A)({key:String(t)},e))}},91371:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>c,contentTitle:()=>u,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var n=a(58168),r=(a(96540),a(15680)),l=(a(67443),a(11470)),i=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 2024",frontMatter:{id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type"}},c={},p=[],d={toc:p},y="wrapper";function h(e){let{components:t,...a}=e;return(0,r.yg)(y,(0,n.A)({},d,a,{components:t,mdxType:"MDXLayout"}),(0,r.yg)("small",null,"Available in GraphQLite 4.0+"),(0,r.yg)("div",{class:"alert alert--info"},"If you are not familiar with the ",(0,r.yg)("code",null,"@Factory")," tag, ",(0,r.yg)("a",{href:"input-types"},'read first the "input types" guide'),"."),(0,r.yg)("p",null,"Fields exposed in a GraphQL input type do not need to be all part of the factory method."),(0,r.yg)("p",null,"Just like with output type (that can be ",(0,r.yg)("a",{parentName:"p",href:"/docs/3.0/extend_type"},"extended using the ",(0,r.yg)("inlineCode",{parentName:"a"},"ExtendType")," annotation"),"), you can extend/modify\nan input type using the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation."),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Decorate")," annotation to add additional fields to an input type that is already declared by a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," annotation,\nor to modify the returned object."),(0,r.yg)("div",{class:"alert alert--info"},"The ",(0,r.yg)("code",null,"@Decorate")," annotation is very useful in scenarios where you cannot touch the ",(0,r.yg)("code",null,"@Factory")," method. This can happen if the ",(0,r.yg)("code",null,"@Factory")," method is defined in a third-party library or if the ",(0,r.yg)("code",null,"@Factory")," method is part of auto-generated code."),(0,r.yg)("p",null,"Let's assume you have a ",(0,r.yg)("inlineCode",{parentName:"p"},"Filter")," class used as an input type. You most certainly have a ",(0,r.yg)("inlineCode",{parentName:"p"},"@Factory")," to create the input type."),(0,r.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"Assuming you ",(0,r.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(i.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(i.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,'In the example above, the "Filter" input type is modified. We add an additional "type" field to the input type.'),(0,r.yg)("p",null,"A few things to notice:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"The decorator takes the object generated by the factory as first argument"),(0,r.yg)("li",{parentName:"ul"},"The decorator MUST return an object of the same type (or a sub-type)"),(0,r.yg)("li",{parentName:"ul"},"The decorator CAN contain additional parameters. They will be added to the fields of the GraphQL input type."),(0,r.yg)("li",{parentName:"ul"},"The ",(0,r.yg)("inlineCode",{parentName:"li"},"@Decorate")," annotation must contain a ",(0,r.yg)("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.yg)("inlineCode",{parentName:"li"},"@Factory"),' annotation, this is by default the name of the\nPHP class + "Input" (for instance: "Filter" => "FilterInput")')),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("strong",null,"Heads up!")," The ",(0,r.yg)("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.yg)("br",null),(0,r.yg)("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/f9af357c.7cb47364.js b/assets/js/f9af357c.bd39cc06.js similarity index 99% rename from assets/js/f9af357c.7cb47364.js rename to assets/js/f9af357c.bd39cc06.js index 5c71a0cc5..ca0f259c8 100644 --- a/assets/js/f9af357c.7cb47364.js +++ b/assets/js/f9af357c.bd39cc06.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8327],{19365:(e,n,t)=>{t.d(n,{A:()=>o});var a=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:n,hidden:t,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>I});var a=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function d(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 h(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??d(t);return function(e){const n=(0,s.X)(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 p(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,l.W6)(),i=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.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function m(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=h(e),[o,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(!p({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:i}))),[u,s]=g({queryString:t,groupId:a}),[d,m]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),y=(()=>{const e=u??d;return p({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),m(e)}),[s,m,i]),tabValues:i}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},p=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 r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function N(e){const n=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function I(e){const n=(0,y.A)();return r.createElement(N,(0,a.A)({key:String(n)},e))}},38273:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>g,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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}],h={toc:d},p="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(p,(0,a.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.yg)("a",{parentName:"li",href:"/docs/5.0/fine-grained-security"},(0,r.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.yg)("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.yg)("br",null),"See ",(0,r.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.yg)("h2",{id:"logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.yg)("p",null,"GraphQLite exposes two annotations (",(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the query ",(0,r.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/5.0/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.yg)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8327],{19365:(e,n,t)=>{t.d(n,{A:()=>o});var a=t(96540),r=t(20053);const i={tabItem:"tabItem_Ymn6"};function o(e){let{children:n,hidden:t,className:o}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.A)(i.tabItem,o),hidden:t},n)}},11470:(e,n,t)=>{t.d(n,{A:()=>I});var a=t(58168),r=t(96540),i=t(20053),o=t(23104),l=t(56347),u=t(57485),s=t(31682),c=t(89466);function d(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 h(e){const{values:n,children:t}=e;return(0,r.useMemo)((()=>{const e=n??d(t);return function(e){const n=(0,s.X)(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 p(e){let{value:n,tabValues:t}=e;return t.some((e=>e.value===n))}function g(e){let{queryString:n=!1,groupId:t}=e;const a=(0,l.W6)(),i=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.aZ)(i),(0,r.useCallback)((e=>{if(!i)return;const n=new URLSearchParams(a.location.search);n.set(i,e),a.replace({...a.location,search:n.toString()})}),[i,a])]}function m(e){const{defaultValue:n,queryString:t=!1,groupId:a}=e,i=h(e),[o,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(!p({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:i}))),[u,s]=g({queryString:t,groupId:a}),[d,m]=function(e){let{groupId:n}=e;const t=function(e){return e?`docusaurus.tab.${e}`:null}(n),[a,i]=(0,c.Dv)(t);return[a,(0,r.useCallback)((e=>{t&&i.set(e)}),[t,i])]}({groupId:a}),y=(()=>{const e=u??d;return p({value:e,tabValues:i})?e:null})();(0,r.useLayoutEffect)((()=>{y&&l(y)}),[y]);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),m(e)}),[s,m,i]),tabValues:i}}var y=t(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:t,selectedValue:l,selectValue:u,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:d}=(0,o.a_)(),h=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},p=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 r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.A)("tabs",{"tabs--block":t},n)},s.map((e=>{let{value:n,label:t,attributes:o}=e;return r.createElement("li",(0,a.A)({role:"tab",tabIndex:l===n?0:-1,"aria-selected":l===n,key:n,ref:e=>c.push(e),onKeyDown:p,onClick:h},o,{className:(0,i.A)("tabs__item",f.tabItem,o?.className,{"tabs__item--active":l===n})}),t??n)})))}function v(e){let{lazy:n,children:t,selectedValue:a}=e;const i=(Array.isArray(t)?t:[t]).filter(Boolean);if(n){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,n)=>(0,r.cloneElement)(e,{key:n,hidden:e.props.value!==a}))))}function N(e){const n=m(e);return r.createElement("div",{className:(0,i.A)("tabs-container",f.tabList)},r.createElement(b,(0,a.A)({},e,n)),r.createElement(v,(0,a.A)({},e,n)))}function I(e){const n=(0,y.A)();return r.createElement(N,(0,a.A)({key:String(n)},e))}},38273:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>u,default:()=>g,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var a=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),o=t(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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}],h={toc:d},p="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(p,(0,a.A)({},h,t,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("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.yg)("p",null,"GraphQLite offers some control over what a user can do with your API. You can restrict access to resources:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},"based on authentication using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Logged")," annotation")," (restrict access to logged users)"),(0,r.yg)("li",{parentName:"ul"},"based on authorization using the ",(0,r.yg)("a",{parentName:"li",href:"#logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"a"},"@Right")," annotation")," (restrict access to logged users with certain rights)."),(0,r.yg)("li",{parentName:"ul"},"based on fine-grained authorization using the ",(0,r.yg)("a",{parentName:"li",href:"/docs/5.0/fine-grained-security"},(0,r.yg)("inlineCode",{parentName:"a"},"@Security")," annotation")," (restrict access for some given resources to some users).")),(0,r.yg)("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.yg)("br",null),"See ",(0,r.yg)("a",{href:"implementing-security"},"Connecting GraphQLite to your framework's security module"),"."),(0,r.yg)("h2",{id:"logged-and-right-annotations"},(0,r.yg)("inlineCode",{parentName:"h2"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"h2"},"@Right")," annotations"),(0,r.yg)("p",null,"GraphQLite exposes two annotations (",(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right"),") that you can use to restrict access to a resource."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"In the example above, the query ",(0,r.yg)("inlineCode",{parentName:"p"},"users")," will only be available if the user making the query is logged AND if he\nhas the ",(0,r.yg)("inlineCode",{parentName:"p"},"CAN_VIEW_USER_LIST")," right."),(0,r.yg)("p",null,(0,r.yg)("inlineCode",{parentName:"p"},"@Logged")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"@Right")," annotations can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("h2",{id:"not-throwing-errors"},"Not throwing errors"),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@FailWith")," annotation contains the value that will be returned for users with insufficient rights."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("h2",{id:"injecting-the-current-user-as-a-parameter"},"Injecting the current user as a parameter"),(0,r.yg)("p",null,"Use the ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation to get an instance of the current user logged in."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@InjectUser")," annotation can be used next to:"),(0,r.yg)("ul",null,(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Query")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Mutation")," annotations"),(0,r.yg)("li",{parentName:"ul"},(0,r.yg)("inlineCode",{parentName:"li"},"@Field")," annotations")),(0,r.yg)("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.yg)("a",{parentName:"p",href:"/docs/5.0/implementing-security"},'"authentication service" configured in GraphQLite'),"."),(0,r.yg)("h2",{id:"hiding-fields--queries--mutations"},"Hiding fields / queries / mutations"),(0,r.yg)("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.yg)("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.yg)("inlineCode",{parentName:"p"},"@HideIfUnauthorized")," annotation."),(0,r.yg)(i.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,r.yg)(o.A,{value:"php8",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)(o.A,{value:"php7",mdxType:"TabItem"},(0,r.yg)("pre",null,(0,r.yg)("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.yg)("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.yg)("div",{class:"alert alert--info"},'The "HideIfUnauthorized" mode was the default mode in GraphQLite 3 and is optionnal from GraphQLite 4+.'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/fa1dd05c.6bfc22c0.js b/assets/js/fa1dd05c.72adee05.js similarity index 99% rename from assets/js/fa1dd05c.6bfc22c0.js rename to assets/js/fa1dd05c.72adee05.js index 117d580b7..b752003a6 100644 --- a/assets/js/fa1dd05c.6bfc22c0.js +++ b/assets/js/fa1dd05c.72adee05.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5511],{15040:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>i,metadata:()=>o,toc:()=>p});var a=t(58168),r=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:n,...i}=e;return(0,r.yg)(y,(0,a.A)({},u,i,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:t(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}h.isMDXComponent=!0},67258:(e,n,t)=>{t.d(n,{A:()=>a});const a=t.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5511],{15040:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>i,metadata:()=>o,toc:()=>p});var a=t(58168),r=(t(96540),t(15680));t(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function h(e){let{components:n,...i}=e;return(0,r.yg)(y,(0,a.A)({},u,i,{components:n,mdxType:"MDXLayout"}),(0,r.yg)("p",null,"In GraphQLite, GraphQL queries are created by writing methods in ",(0,r.yg)("em",{parentName:"p"},"controller")," classes."),(0,r.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Controller")," by default."),(0,r.yg)("h2",{id:"simple-query"},"Simple query"),(0,r.yg)("p",null,"In a controller class, each query method must be annotated with the ",(0,r.yg)("inlineCode",{parentName:"p"},"@Query")," annotation. For instance:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Query {\n hello(name: String!): String!\n}\n")),(0,r.yg)("p",null,"As you can see, GraphQLite will automatically do the mapping between PHP types and GraphQL types."),(0,r.yg)("div",{class:"alert alert--warning"},(0,r.yg)("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.yg)("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.yg)("h2",{id:"testing-the-query"},"Testing the query"),(0,r.yg)("p",null,"The default GraphQL endpoint is ",(0,r.yg)("inlineCode",{parentName:"p"},"/graphql"),"."),(0,r.yg)("p",null,"The easiest way to test a GraphQL endpoint is to use ",(0,r.yg)("a",{parentName:"p",href:"https://github.com/graphql/graphiql"},"GraphiQL")," or\n",(0,r.yg)("a",{parentName:"p",href:"https://altair.sirmuel.design/"},"Altair")," clients (they are available as Chrome or Firefox plugins)"),(0,r.yg)("div",{class:"alert alert--info"},"If you are using the Symfony bundle, GraphiQL is also directly embedded.",(0,r.yg)("br",null),"Simply head to ",(0,r.yg)("code",null,"http://[path-to-my-app]/graphiql")),(0,r.yg)("p",null,"Here a query using our simple ",(0,r.yg)("em",{parentName:"p"},"Hello World")," example:"),(0,r.yg)("p",null,(0,r.yg)("img",{src:t(67258).A,width:"1132",height:"352"})),(0,r.yg)("h2",{id:"query-with-a-type"},"Query with a type"),(0,r.yg)("p",null,"So far, we simply declared a query. But we did not yet declare a type."),(0,r.yg)("p",null,"Let's assume you want to return a product:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"As the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is not a scalar type, you must tell GraphQLite how to handle it:"),(0,r.yg)("pre",null,(0,r.yg)("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.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Type")," annotation is used to inform GraphQLite that the ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class is a GraphQL type."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"@Field")," annotation is used to define the GraphQL fields. This annotation must be put on a ",(0,r.yg)("strong",{parentName:"p"},"public method"),"."),(0,r.yg)("p",null,"The ",(0,r.yg)("inlineCode",{parentName:"p"},"Product")," class must be in one of the ",(0,r.yg)("em",{parentName:"p"},"types")," namespaces. As for ",(0,r.yg)("em",{parentName:"p"},"controller")," classes, you configured this namespace when you installed\nGraphQLite. By default, in Symfony, the allowed types namespaces are ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Entity")," and ",(0,r.yg)("inlineCode",{parentName:"p"},"App\\Types"),"."),(0,r.yg)("p",null,"This query is equivalent to the following ",(0,r.yg)("a",{parentName:"p",href:"https://graphql.org/learn/schema/#type-language"},"GraphQL type language"),":"),(0,r.yg)("pre",null,(0,r.yg)("code",{parentName:"pre",className:"language-graphql"},"Type Product {\n name: String!\n price: Float\n}\n")),(0,r.yg)("div",{class:"alert alert--info"},(0,r.yg)("p",null,"If you are used to ",(0,r.yg)("a",{href:"https://en.wikipedia.org/wiki/Domain-driven_design"},"Domain driven design"),", you probably realize that the ",(0,r.yg)("code",null,"Product")," class is part of your ",(0,r.yg)("i",null,"domain"),"."),(0,r.yg)("p",null,"GraphQL annotations are adding some serialization logic that is out of scope of the domain. These are ",(0,r.yg)("i",null,"just")," annotations and for most project, this is the fastest and easiest route."),(0,r.yg)("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.")))}h.isMDXComponent=!0},67258:(e,n,t)=>{t.d(n,{A:()=>a});const a=t.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/fa41c0e9.5ce1513d.js b/assets/js/fa41c0e9.957dcfcd.js similarity index 99% rename from assets/js/fa41c0e9.5ce1513d.js rename to assets/js/fa41c0e9.957dcfcd.js index 8e4b67a61..4dc2122b0 100644 --- a/assets/js/fa41c0e9.5ce1513d.js +++ b/assets/js/fa41c0e9.957dcfcd.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1538],{19365:(e,n,a)=>{a.d(n,{A:()=>r});var t=a(96540),p=a(20053);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:a,className:r}=e;return t.createElement("div",{role:"tabpanel",className:(0,p.A)(l.tabItem,r),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>N});var t=a(58168),p=a(96540),l=a(20053),r=a(23104),s=a(56347),i=a(57485),u=a(31682),o=a(89466);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:a,attributes:t,default:p}}=e;return{value:n,label:a,attributes:t,default:p}}))}function m(e){const{values:n,children:a}=e;return(0,p.useMemo)((()=>{const e=n??c(a);return function(e){const n=(0,u.X)(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,a])}function y(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,i.aZ)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function g(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!y({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[i,u]=d({queryString:a,groupId:t}),[c,g]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,p.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=i??c;return y({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{h&&s(h)}),[h]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!y({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 h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=u[a].value;t!==s&&(c(n),i(t))},y=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},u.map((e=>{let{value:n,label:a,attributes:r}=e;return p.createElement("li",(0,t.A)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:y,onClick:m},r,{className:(0,l.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function T(e){const n=g(e);return p.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},p.createElement(b,(0,t.A)({},e,n)),p.createElement(v,(0,t.A)({},e,n)))}function N(e){const n=(0,h.A)();return p.createElement(T,(0,t.A)({key:String(n)},e))}},15801:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>i,default:()=>d,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var t=a(58168),p=(a(96540),a(15680)),l=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.2/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.2/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"You can create a GraphQL union type ",(0,p.yg)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.yg)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.yg)("p",null,"You will first need to install ",(0,p.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("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.yg)("em",null,"type mappers")," in the ",(0,p.yg)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.yg)("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.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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([[1538],{19365:(e,n,a)=>{a.d(n,{A:()=>r});var t=a(96540),p=a(20053);const l={tabItem:"tabItem_Ymn6"};function r(e){let{children:n,hidden:a,className:r}=e;return t.createElement("div",{role:"tabpanel",className:(0,p.A)(l.tabItem,r),hidden:a},n)}},11470:(e,n,a)=>{a.d(n,{A:()=>N});var t=a(58168),p=a(96540),l=a(20053),r=a(23104),s=a(56347),i=a(57485),u=a(31682),o=a(89466);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:a,attributes:t,default:p}}=e;return{value:n,label:a,attributes:t,default:p}}))}function m(e){const{values:n,children:a}=e;return(0,p.useMemo)((()=>{const e=n??c(a);return function(e){const n=(0,u.X)(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,a])}function y(e){let{value:n,tabValues:a}=e;return a.some((e=>e.value===n))}function d(e){let{queryString:n=!1,groupId:a}=e;const t=(0,s.W6)(),l=function(e){let{queryString:n=!1,groupId:a}=e;if("string"==typeof n)return n;if(!1===n)return null;if(!0===n&&!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:n,groupId:a});return[(0,i.aZ)(l),(0,p.useCallback)((e=>{if(!l)return;const n=new URLSearchParams(t.location.search);n.set(l,e),t.replace({...t.location,search:n.toString()})}),[l,t])]}function g(e){const{defaultValue:n,queryString:a=!1,groupId:t}=e,l=m(e),[r,s]=(0,p.useState)((()=>function(e){let{defaultValue:n,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(n){if(!y({value:n,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${n}" 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 n}const t=a.find((e=>e.default))??a[0];if(!t)throw new Error("Unexpected error: 0 tabValues");return t.value}({defaultValue:n,tabValues:l}))),[i,u]=d({queryString:a,groupId:t}),[c,g]=function(e){let{groupId:n}=e;const a=function(e){return e?`docusaurus.tab.${e}`:null}(n),[t,l]=(0,o.Dv)(a);return[t,(0,p.useCallback)((e=>{a&&l.set(e)}),[a,l])]}({groupId:t}),h=(()=>{const e=i??c;return y({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{h&&s(h)}),[h]);return{selectedValue:r,selectValue:(0,p.useCallback)((e=>{if(!y({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 h=a(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:n,block:a,selectedValue:s,selectValue:i,tabValues:u}=e;const o=[],{blockElementScrollPositionUntilNextRender:c}=(0,r.a_)(),m=e=>{const n=e.currentTarget,a=o.indexOf(n),t=u[a].value;t!==s&&(c(n),i(t))},y=e=>{let n=null;switch(e.key){case"Enter":m(e);break;case"ArrowRight":{const a=o.indexOf(e.currentTarget)+1;n=o[a]??o[0];break}case"ArrowLeft":{const a=o.indexOf(e.currentTarget)-1;n=o[a]??o[o.length-1];break}}n?.focus()};return p.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.A)("tabs",{"tabs--block":a},n)},u.map((e=>{let{value:n,label:a,attributes:r}=e;return p.createElement("li",(0,t.A)({role:"tab",tabIndex:s===n?0:-1,"aria-selected":s===n,key:n,ref:e=>o.push(e),onKeyDown:y,onClick:m},r,{className:(0,l.A)("tabs__item",f.tabItem,r?.className,{"tabs__item--active":s===n})}),a??n)})))}function v(e){let{lazy:n,children:a,selectedValue:t}=e;const l=(Array.isArray(a)?a:[a]).filter(Boolean);if(n){const e=l.find((e=>e.props.value===t));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!==t}))))}function T(e){const n=g(e);return p.createElement("div",{className:(0,l.A)("tabs-container",f.tabList)},p.createElement(b,(0,t.A)({},e,n)),p.createElement(v,(0,t.A)({},e,n)))}function N(e){const n=(0,h.A)();return p.createElement(T,(0,t.A)({key:String(n)},e))}},15801:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>o,contentTitle:()=>i,default:()=>d,frontMatter:()=>s,metadata:()=>u,toc:()=>c});var t=a(58168),p=(a(96540),a(15680)),l=(a(67443),a(11470)),r=a(19365);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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},y="wrapper";function d(e){let{components:n,...a}=e;return(0,p.yg)(y,(0,t.A)({},m,a,{components:n,mdxType:"MDXLayout"}),(0,p.yg)("p",null,"As explained in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.2/queries"},"queries")," section, the job of GraphQLite is to create GraphQL types from PHP types."),(0,p.yg)("h2",{id:"scalar-mapping"},"Scalar mapping"),(0,p.yg)("p",null,"Scalar PHP types can be type-hinted to the corresponding GraphQL types:"),(0,p.yg)("ul",null,(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"string")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"int")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"bool")),(0,p.yg)("li",{parentName:"ul"},(0,p.yg)("inlineCode",{parentName:"li"},"float"))),(0,p.yg)("p",null,"For instance:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"class-mapping"},"Class mapping"),(0,p.yg)("p",null,"When returning a PHP class in a query, you must annotate this class using ",(0,p.yg)("inlineCode",{parentName:"p"},"@Type")," and ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotations:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"App\\Entities\\Product"),', then the GraphQL type will be named "Product".'),(0,p.yg)("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.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Type(name: "MyProduct")]\nclass Product { /* ... */ }\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Type(name="MyProduct")\n */\nclass Product { /* ... */ }\n')))),(0,p.yg)("div",{class:"alert alert--info"},"You can also put a ",(0,p.yg)("a",{href:"inheritance-interfaces#mapping-interfaces"},(0,p.yg)("code",null,"@Type")," annotation on a PHP interface to map your code to a GraphQL interface"),"."),(0,p.yg)("h2",{id:"array-mapping"},"Array mapping"),(0,p.yg)("p",null,"You can type-hint against arrays (or iterators) as long as you add a detailed ",(0,p.yg)("inlineCode",{parentName:"p"},"@return")," statement in the PHPDoc."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"id-mapping"},"ID mapping"),(0,p.yg)("p",null,"GraphQL comes with a native ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," type. PHP has no such type."),(0,p.yg)("p",null,"There are two ways with GraphQLite to handle such type."),(0,p.yg)("h3",{id:"force-the-outputtype"},"Force the outputType"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'#[Field(outputType: "ID")]\npublic function getId(): string\n{\n // ...\n}\n'))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},'/**\n * @Field(outputType="ID")\n */\npublic function getId(): string\n{\n // ...\n}\n')))),(0,p.yg)("p",null,"Using the ",(0,p.yg)("inlineCode",{parentName:"p"},"outputType")," attribute of the ",(0,p.yg)("inlineCode",{parentName:"p"},"@Field")," annotation, you can force the output type to ",(0,p.yg)("inlineCode",{parentName:"p"},"ID"),"."),(0,p.yg)("p",null,"You can learn more about forcing output types in the ",(0,p.yg)("a",{parentName:"p",href:"/docs/4.2/custom-types"},"custom types section"),"."),(0,p.yg)("h3",{id:"id-class"},"ID class"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"use TheCodingMachine\\GraphQLite\\Types\\ID;\n\n#[Field]\npublic function getId(): ID\n{\n // ...\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"Note that you can also use the ",(0,p.yg)("inlineCode",{parentName:"p"},"ID")," class as an input type:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"date-mapping"},"Date mapping"),(0,p.yg)("p",null,"Out of the box, GraphQL does not have a ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," type, but we took the liberty to add one, with sensible defaults."),(0,p.yg)("p",null,"When used as an output type, ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeImmutable")," or ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTimeInterface")," PHP classes are\nautomatically mapped to this ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime")," GraphQL type."),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"#[Field]\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n"))),(0,p.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-php"},"/**\n * @Field\n */\npublic function getDate(): \\DateTimeInterface\n{\n return $this->date;\n}\n")))),(0,p.yg)("p",null,"The ",(0,p.yg)("inlineCode",{parentName:"p"},"date")," field will be of type ",(0,p.yg)("inlineCode",{parentName:"p"},"DateTime"),". In the returned JSON response to a query, the date is formatted as a string\nin the ",(0,p.yg)("strong",{parentName:"p"},"ISO8601")," format (aka ATOM format)."),(0,p.yg)("div",{class:"alert alert--danger"},"PHP ",(0,p.yg)("code",null,"DateTime")," type is not supported."),(0,p.yg)("h2",{id:"union-types"},"Union types"),(0,p.yg)("p",null,"You can create a GraphQL union type ",(0,p.yg)("em",{parentName:"p"},"on the fly")," using the pipe ",(0,p.yg)("inlineCode",{parentName:"p"},"|")," operator in the PHPDoc:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"enum-types"},"Enum types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum")," and GraphQLite comes with\nnative support for it."),(0,p.yg)("p",null,"You will first need to install ",(0,p.yg)("a",{parentName:"p",href:"https://github.com/myclabs/php-enum"},"myclabs/php-enum"),":"),(0,p.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-bash"},"$ composer require myclabs/php-enum\n")),(0,p.yg)("p",null,"Now, any class extending the ",(0,p.yg)("inlineCode",{parentName:"p"},"MyCLabs\\Enum\\Enum")," class will be mapped to a GraphQL enum:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("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.yg)("pre",null,(0,p.yg)("code",{parentName:"pre",className:"language-graphql"},"query users($status: StatusEnum!) {}\n users(status: $status) {\n id\n }\n}\n")),(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"@EnumType")," annotation:"),(0,p.yg)(l.A,{defaultValue:"php8",values:[{label:"PHP 8",value:"php8"},{label:"PHP 7",value:"php7"}],mdxType:"Tabs"},(0,p.yg)(r.A,{value:"php8",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)(r.A,{value:"php7",mdxType:"TabItem"},(0,p.yg)("pre",null,(0,p.yg)("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.yg)("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.yg)("strong",null,"your enum classes MUST be in one of the namespaces declared for the types in your GraphQLite configuration file.")),(0,p.yg)("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.yg)("em",null,"type mappers")," in the ",(0,p.yg)("a",{href:"internals"},'"internals" documentation'),"and ",(0,p.yg)("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.yg)("h2",{id:"deprecation-of-fields"},"Deprecation of fields"),(0,p.yg)("p",null,"You can mark a field as deprecated in your GraphQL Schema by just annotating it with the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," PHPDoc annotation."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("p",null,"This will add the ",(0,p.yg)("inlineCode",{parentName:"p"},"@deprecated")," directive to the field in the GraphQL Schema which sets the ",(0,p.yg)("inlineCode",{parentName:"p"},"isDeprecated")," field to ",(0,p.yg)("inlineCode",{parentName:"p"},"true")," and adds the reason to the ",(0,p.yg)("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.yg)("inlineCode",{parentName:"p"},"includeDeprecated")," is set to ",(0,p.yg)("inlineCode",{parentName:"p"},"true"),"."),(0,p.yg)("pre",null,(0,p.yg)("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.yg)("h2",{id:"more-scalar-types"},"More scalar types"),(0,p.yg)("small",null,"Available in GraphQLite 4.0+"),(0,p.yg)("p",null,'GraphQL supports "custom" scalar types. GraphQLite supports adding more GraphQL scalar types.'),(0,p.yg)("p",null,"If you need more types, you can check the ",(0,p.yg)("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.yg)("p",null,"Or if you have some special needs, ",(0,p.yg)("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/fe153c07.0f6f610e.js b/assets/js/fe153c07.ca5ec74e.js similarity index 99% rename from assets/js/fe153c07.0f6f610e.js rename to assets/js/fe153c07.ca5ec74e.js index d8d698518..2d75ba440 100644 --- a/assets/js/fe153c07.0f6f610e.js +++ b/assets/js/fe153c07.ca5ec74e.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8059],{16949:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>l,toc:()=>p});var r=a(58168),t=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734526208,formattedLastUpdatedAt:"Dec 18, 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.yg)(u,(0,r.A)({},c,o,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("p",null,"If you are using ",(0,t.yg)("strong",{parentName:"p"},"Symfony 4.x"),", checkout the ",(0,t.yg)("a",{parentName:"p",href:"/docs/3.0/symfony-bundle"},"Symfony bundle"),"."),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/phps-cans/psr7-middleware-graphql"},"PSR-15 middleware available"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("h2",{id:"advanced-example"},"Advanced example"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("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.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-7 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"phps-cans/psr7-middleware-graphql")," to route PSR-7 requests to the GraphQL engine"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"composer.json")),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"index.php")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/container.php")),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"src/Controllers/MyController.php")),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/container.php")),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."),(0,t.yg)("p",null,(0,t.yg)("img",{src:a(67258).A,width:"1132",height:"352"})))}h.isMDXComponent=!0},67258:(e,n,a)=>{a.d(n,{A:()=>r});const r=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8059],{16949:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>h,frontMatter:()=>o,metadata:()=>l,toc:()=>p});var r=a(58168),t=(a(96540),a(15680));a(67443);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:"Jacob Thomason",lastUpdatedAt:1734528123,formattedLastUpdatedAt:"Dec 18, 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.yg)(u,(0,r.A)({},c,o,{components:n,mdxType:"MDXLayout"}),(0,t.yg)("p",null,"If you are using ",(0,t.yg)("strong",{parentName:"p"},"Symfony 4.x"),", checkout the ",(0,t.yg)("a",{parentName:"p",href:"/docs/3.0/symfony-bundle"},"Symfony bundle"),"."),(0,t.yg)("h2",{id:"installation"},"Installation"),(0,t.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite\n")),(0,t.yg)("h2",{id:"requirements"},"Requirements"),(0,t.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"A PSR-11 compatible container"),(0,t.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,t.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,t.yg)("p",null,"GraphQLite relies on the ",(0,t.yg)("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.yg)("a",{parentName:"p",href:"https://github.com/phps-cans/psr7-middleware-graphql"},"PSR-15 middleware available"),"."),(0,t.yg)("h2",{id:"integration"},"Integration"),(0,t.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,t.yg)("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.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class to create such a schema:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"You can now use this schema with ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/getting-started/#hello-world"},"Webonyx GraphQL facade"),"\nor the ",(0,t.yg)("a",{parentName:"p",href:"https://webonyx.github.io/graphql-php/executing-queries/#using-server"},"StandardServer class"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"SchemaFactory")," class also comes with a number of methods that you can use to customize your GraphQLite settings."),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("h2",{id:"minimal-example"},"Minimal example"),(0,t.yg)("p",null,"The smallest working example using no framework is:"),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("h2",{id:"advanced-example"},"Advanced example"),(0,t.yg)("p",null,"When using a framework, you will need a way to route your HTTP requests to the ",(0,t.yg)("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.yg)("p",null,"In this example, we will focus on getting a working version of GraphQLite using:"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("a",{parentName:"li",href:"https://docs.zendframework.com/zend-stratigility/"},"Zend Stratigility")," as a PSR-7 server"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"phps-cans/psr7-middleware-graphql")," to route PSR-7 requests to the GraphQL engine"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"mouf/picotainer")," (a micro-container) for the PSR-11 container"),(0,t.yg)("li",{parentName:"ul"},(0,t.yg)("inlineCode",{parentName:"li"},"symfony/cache ")," for the PSR-16 cache")),(0,t.yg)("p",null,"The choice of the libraries is really up to you. You can adapt it based on your needs."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"composer.json")),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"index.php")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-php"},"get(MiddlewarePipe::class),\n new SapiStreamEmitter(),\n $serverRequestFactory,\n $errorResponseGenerator\n);\n$runner->run();\n")),(0,t.yg)("p",null,"Here we are initializing a Zend ",(0,t.yg)("inlineCode",{parentName:"p"},"RequestHandler")," (it receives requests) and we pass it to a Zend Stratigility ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe"),".\nThis ",(0,t.yg)("inlineCode",{parentName:"p"},"MiddlewarePipe")," comes from the container declared in the ",(0,t.yg)("inlineCode",{parentName:"p"},"config/container.php")," file:"),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/container.php")),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"Now, we need to add a first query and therefore create a controller.\nThe application will look into the ",(0,t.yg)("inlineCode",{parentName:"p"},"App\\Controllers")," namespace for GraphQLite controllers."),(0,t.yg)("p",null,"It assumes that the container has an entry whose name is the controller's fully qualified class name."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"src/Controllers/MyController.php")),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"config/container.php")),(0,t.yg)("pre",null,(0,t.yg)("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.yg)("p",null,"And we are done! You can now test your query using your favorite GraphQL client."),(0,t.yg)("p",null,(0,t.yg)("img",{src:a(67258).A,width:"1132",height:"352"})))}h.isMDXComponent=!0},67258:(e,n,a)=>{a.d(n,{A:()=>r});const r=a.p+"assets/images/query1-5a22bbe2398efcc725ea571a07ff2c9b.png"}}]); \ No newline at end of file diff --git a/assets/js/runtime~main.dd419208.js b/assets/js/runtime~main.d8dde0e5.js similarity index 61% rename from assets/js/runtime~main.dd419208.js rename to assets/js/runtime~main.d8dde0e5.js index 65f100ae1..ae23fd136 100644 --- a/assets/js/runtime~main.dd419208.js +++ b/assets/js/runtime~main.d8dde0e5.js @@ -1 +1 @@ -(()=>{"use strict";var e,c,a,b,f={},d={};function r(e){var c=d[e];if(void 0!==c)return c.exports;var a=d[e]={exports:{}};return f[e].call(a.exports,a,a.exports,r),a.exports}r.m=f,e=[],r.O=(c,a,b,f)=>{if(!a){var d=1/0;for(i=0;i=f)&&Object.keys(r.O).every((e=>r.O[e](a[o])))?a.splice(o--,1):(t=!1,f0&&e[i-1][2]>f;i--)e[i]=e[i-1];e[i]=[a,b,f]},r.n=e=>{var c=e&&e.__esModule?()=>e.default:()=>e;return r.d(c,{a:c}),c},a=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(e,b){if(1&b&&(e=this(e)),8&b)return e;if("object"==typeof e&&e){if(4&b&&e.__esModule)return e;if(16&b&&"function"==typeof e.then)return e}var f=Object.create(null);r.r(f);var d={};c=c||[null,a({}),a([]),a(a)];for(var t=2&b&&e;"object"==typeof t&&!~c.indexOf(t);t=a(t))Object.getOwnPropertyNames(t).forEach((c=>d[c]=()=>e[c]));return d.default=()=>e,r.d(f,d),f},r.d=(e,c)=>{for(var a in c)r.o(c,a)&&!r.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:c[a]})},r.f={},r.e=e=>Promise.all(Object.keys(r.f).reduce(((c,a)=>(r.f[a](e,c),c)),[])),r.u=e=>"assets/js/"+({2:"e196b408",40:"1e138b9d",68:"a27ea030",79:"1e7fe27e",81:"58d52345",104:"5e352ef4",109:"8f967659",152:"c7e7ae18",211:"652c74f1",222:"4bdafdff",229:"767c28af",247:"beccb025",288:"5dde70bf",321:"f2710c27",324:"f309eabc",362:"085c135f",436:"68b7d615",458:"2bbfc5d5",464:"a3a193a6",481:"b5d32d98",501:"a30fd8ca",514:"08fe23a4",521:"c007fb39",540:"7f74c501",552:"b35d1284",573:"89ed63c8",629:"a9bc4f03",630:"ac8293fa",651:"bb5ef1b7",663:"b6722b03",770:"f7c03581",776:"e126d786",835:"a13f3cdc",862:"606959d6",932:"0e5befdb",958:"48fde361",1027:"528fe65e",1039:"eca0cf35",1062:"a27f6be0",1084:"b2d9540a",1126:"4dfeb783",1133:"eaa287f0",1141:"c4d37b36",1188:"6c14a231",1190:"6d89025c",1235:"c10d4a63",1245:"1edb88e5",1264:"18100524",1289:"02c5a8b1",1308:"c7a4caa1",1340:"4f59166d",1345:"2e25c87f",1431:"1ca907c0",1443:"4d68b066",1465:"d9523c62",1481:"b26a5b84",1505:"8f7fa040",1538:"fa41c0e9",1565:"9bd507da",1585:"843ebfb4",1587:"3c86ad25",1604:"4dd5816e",1653:"21cde469",1661:"d8ff000f",1674:"2f36012a",1763:"2fc68ddc",1766:"e39283a8",1776:"23794275",1886:"b4657038",1894:"aa5b6080",1898:"95576100",1930:"55c77f1e",1950:"23a8ac29",1968:"c3701568",1975:"7ade2db5",1985:"27258a7d",2032:"9000b231",2076:"common",2089:"b69ed219",2112:"1ea13486",2113:"cd25a595",2119:"e7ffb4b4",2138:"1a4e3797",2156:"4d049718",2174:"07666c14",2187:"dc9a99e0",2197:"94ecc552",2207:"1aa05129",2227:"0db959c8",2230:"8b6bafea",2235:"3d2d0a86",2248:"c275698c",2275:"5ececfab",2301:"a9125b44",2311:"bfe5398f",2347:"5e21a9be",2358:"aa675676",2369:"079b0d3e",2400:"7ee46e43",2421:"f4e1d1ba",2459:"25d4129e",2491:"1e2c5f46",2589:"4f4b6633",2592:"8f7abfe1",2596:"1d20a4b3",2600:"e7672013",2605:"c5fa393d",2634:"c4f5d8e4",2674:"ca36df4d",2676:"5ec7a7fe",2720:"4c5bf49d",2743:"01fe3043",2784:"69f2ab1f",2830:"b9ea999a",2858:"29cf2ad6",2862:"7e507331",2917:"36ddade1",2935:"0df2ba32",2952:"bcc01c83",2958:"db6a6f31",2960:"64536e1a",2962:"1f5af0f2",2964:"23f642f2",2965:"1af245cd",2998:"ae0a12ed",3088:"242d99d9",3126:"4aab8b8c",3137:"4f6c3156",3177:"cc1f18af",3195:"7d4976a8",3196:"bcb6471f",3308:"9953ecde",3332:"71a56230",3343:"b5d0ac54",3355:"5fa4a5b6",3359:"e91daeb9",3382:"21a7a3b0",3419:"756c6ac7",3449:"e617c97b",3457:"5e457383",3460:"1891fd2b",3468:"68e30702",3507:"77cdcd82",3565:"3a3e6a89",3576:"82395e72",3585:"3f944aba",3610:"579cc8d4",3613:"22e1e32f",3642:"263ebc7a",3672:"b103c05a",3693:"5a9b411c",3701:"8d81badd",3712:"d49884c9",3723:"1428bdad",3765:"0343976d",3781:"b7442939",3811:"4445fe20",3820:"24aca886",3955:"aba5bf07",3962:"16565e6a",4e3:"ce95b17c",4017:"9073923c",4021:"03abab96",4032:"56279b5e",4053:"78da31a1",4054:"20540af3",4086:"6b4e0fb4",4103:"d07ad772",4116:"cddcd4e6",4122:"5ffc8074",4124:"e8a97ac3",4224:"a16ee953",4225:"38317547",4253:"87089bce",4279:"610e7425",4299:"5b80a12a",4324:"e806c7bf",4330:"65b8d1d1",4366:"16017aa6",4368:"56af72f6",4393:"27e787ca",4422:"18d6c9c9",4438:"7afb60b1",4474:"a7159008",4485:"59b1a96c",4513:"d3540d59",4548:"d8037f4c",4565:"7b54f5d5",4619:"a228ae9b",4620:"05fed6b1",4664:"e4c5fdc3",4671:"1d703573",4690:"f48e2589",4706:"2f46a9d9",4716:"ba7653ad",4761:"1e6ec01e",4762:"232afa3a",4773:"5945e8b0",4779:"a320b509",4780:"332827b4",4803:"06c02cc7",4805:"6efd6ec9",4807:"d4446569",4827:"03c886f6",4840:"e688cd7e",4843:"4e1a0951",4876:"a0bf4a5f",4884:"74383bd8",4893:"9f0ecd2e",4919:"aa52484c",4954:"26a27afb",4955:"b6a6a31f",4978:"e5d0e3cb",4981:"4e73bd72",5e3:"2d02c83c",5011:"c953ec08",5049:"bdb33130",5083:"73ccb1b9",5091:"05e8cfc0",5099:"1b1927f4",5138:"b4aea2ce",5170:"6c8ff36a",5180:"366cfce3",5198:"143f7888",5235:"6fe30f11",5281:"cd699560",5282:"eec7caa6",5316:"c8bdc4df",5356:"60d99771",5362:"323a980a",5409:"38cf1c7a",5473:"3b58261a",5511:"fa1dd05c",5515:"cc08685c",5518:"e347e63a",5526:"96877411",5547:"565a5567",5558:"3d0eb74d",5619:"7bf967bc",5646:"612b773e",5675:"5285d58e",5730:"32e2b5e3",5738:"eb333c39",5747:"b370b50c",5761:"0fad1f8b",5762:"6c124661",5766:"8e97f284",5779:"85c72337",5830:"f90c5a21",5832:"bb9fe7c3",5856:"90e0b7fd",5884:"e29eb381",5923:"27b414e3",5962:"95073452",5981:"0d7bb119",6009:"8299d165",6053:"17cca601",6086:"136c1ee9",6088:"13b4aeb1",6095:"741df2ae",6123:"a2d3d8d2",6145:"2355609d",6151:"c933a311",6158:"0fd21208",6192:"c69dda99",6205:"4ed8ec4c",6209:"78619623",6219:"a91c1a62",6253:"999289d8",6266:"be1f0304",6337:"a28aff23",6361:"d74b5642",6364:"d4a334ea",6369:"96fc29fc",6408:"107b7a36",6427:"b42f5805",6473:"107d11ee",6481:"2014e4e3",6487:"8223875c",6523:"8bf32d27",6537:"4a2da18c",6556:"d6b4b60c",6579:"d7067606",6599:"029c6d75",6621:"61c7d915",6628:"b94a1068",6681:"9bbf4a9a",6700:"394f3211",6714:"2b6906c9",6729:"15a79915",6730:"6ad31330",6766:"54ca8693",6874:"bda39da3",6894:"504e6c2d",6912:"c1fe0282",6918:"32562f03",6924:"617523b3",6925:"07623f9a",6931:"28c12eaf",6961:"400ddbbb",6972:"31b4e903",6981:"ece9cf29",6984:"7e63a40e",6986:"077a13b8",7035:"72d0dc3a",7041:"607daa94",7042:"12d3ef9e",7045:"72be5fd7",7107:"04610919",7110:"9749ab4a",7116:"4194805f",7141:"85339969",7143:"e6858589",7146:"5d95c2e4",7200:"1520c72c",7248:"e38ecde0",7258:"f9511b3d",7321:"26662da3",7326:"673df5d6",7341:"f07f4757",7362:"766e1cc8",7371:"c6df2ddc",7373:"f5b0a435",7382:"822cd419",7471:"0a57d896",7483:"30940d42",7492:"cc1c02fe",7542:"a264d631",7544:"9664ee55",7575:"8913b51a",7591:"1f5e9707",7696:"9206a32f",7735:"54c144e4",7757:"380575ae",7800:"623b6c78",7846:"947f2c39",7858:"89cae3a7",7868:"8e2662b8",7906:"b06c439f",7924:"d589d3a7",7938:"51b7da58",7940:"b0ed7ea5",7942:"354a9b78",8023:"15b5a907",8025:"dbf2bcb3",8028:"0db009bb",8042:"29a6c1ba",8055:"e1b8bb84",8059:"fe153c07",8060:"dab32d56",8087:"6a8c9872",8093:"a23a5b68",8100:"3b486936",8107:"e45c611c",8112:"0cb7e976",8166:"471c3e37",8173:"e68b092b",8177:"cf877cff",8194:"950394a4",8260:"e63ebe23",8267:"50122f86",8309:"a95c9e82",8313:"379bfe51",8327:"f9af357c",8330:"d62b7e4c",8350:"6c4340be",8357:"aebf35b6",8372:"57f5c28c",8401:"17896441",8414:"c0fa6485",8457:"509d2004",8470:"1ba75d10",8478:"2d4548df",8483:"acbaac14",8526:"b8487569",8542:"b9d6d6e5",8548:"346bcb92",8581:"935f2afb",8588:"a3c6f073",8607:"c1068675",8621:"4a07aaf0",8628:"5881f7ec",8633:"07c49ebd",8688:"4d00e03a",8703:"cb01db44",8714:"1be78505",8718:"75cc8326",8722:"64947e00",8735:"2917b31e",8798:"6cfcfcfb",8868:"f9063551",8871:"5fb37434",8873:"17518879",8919:"bf2a5963",8933:"f94b062c",8945:"e2e51976",8950:"ed0c0463",8997:"4a060504",9008:"24ac61c7",9013:"9d9f8394",9026:"bd2c4a98",9032:"21637dff",9040:"e5d7b215",9062:"caa79efa",9092:"2ef99682",9096:"7b417fb4",9097:"102de343",9127:"2b26025e",9158:"8c95fc16",9219:"36b1b0cc",9227:"7c27e34c",9249:"c329487f",9255:"0ef60658",9262:"9279cea7",9271:"7810a993",9282:"d4c8693b",9336:"5d7590c2",9368:"2830ce57",9439:"8f951ce3",9441:"a55b0daf",9445:"6c6ce37c",9454:"5bc7272e",9472:"4c7f7507",9581:"4f30448a",9594:"c32ff706",9606:"5792f9ba",9624:"2e301473",9661:"cd30f404",9717:"976f6afc",9742:"820db038",9775:"61595218",9778:"9d336ee4",9793:"0370fbfb",9798:"58e6b30f",9810:"859fcda7",9828:"d6188fd4",9866:"a99e9943",9870:"7515d7ec",9917:"91e22cb6",9949:"a1e3d512"}[e]||e)+"."+{2:"a78dca45",40:"af88d16b",68:"bb1f8d85",79:"a69acb67",81:"1f7e6858",104:"a0ec87fc",109:"9b309dd8",152:"90632fce",211:"6f8e2dfd",222:"edd05d37",229:"f76bd5cf",247:"2bce8e1f",288:"4154cee0",321:"7e389950",324:"17fc6e9e",362:"62109324",416:"85e975e8",436:"460d30f2",458:"6351af1c",464:"9cd17649",481:"83d31ffc",501:"6e705d12",514:"0c7fa6f6",521:"c1bd0f68",540:"fe3b3a48",552:"a50b0cce",573:"2ff7c8bc",629:"08cf572d",630:"486d62f6",651:"9dc60367",663:"4c0cf4e3",770:"64966720",776:"6b032437",835:"739720d4",862:"c75b1bce",932:"e4236bca",958:"7161dff2",1027:"145effa3",1039:"fa28893f",1062:"c080cf87",1084:"5ed5cc8c",1126:"8925d06c",1133:"70bd8003",1141:"db54eec4",1188:"3e308cd7",1190:"6b2e999b",1235:"1fc0f2a8",1245:"94425734",1264:"82b29572",1289:"1846c306",1308:"e682f287",1340:"c301b60f",1345:"1ae4714b",1431:"c014be77",1443:"70c9c17d",1465:"557f0440",1481:"39f17309",1505:"2b316d49",1538:"5ce1513d",1565:"8a54c024",1585:"b37baa9b",1587:"fffa6c7c",1604:"f6f4f160",1653:"cb440bf0",1661:"410fde9c",1674:"47f01b7f",1763:"8512b0e9",1766:"3578b356",1774:"9b58a5d2",1776:"7217b836",1886:"3d7bc7ef",1894:"41588e8b",1898:"d95ae89b",1930:"e707d5c7",1950:"22cce971",1968:"dbcc1dc8",1975:"8dd4e724",1985:"c0f5f2d7",2032:"83f9d52f",2076:"8b81e25b",2089:"14a7f32f",2112:"734e5d0e",2113:"a0197dfd",2119:"d8e071f0",2138:"f477ed0f",2156:"9120e91e",2174:"2332900a",2187:"fb28ae35",2197:"4ea01d21",2207:"6d8f74c5",2227:"7a233fd1",2230:"c7a6cf4f",2235:"e2343eb4",2248:"69c19950",2275:"58345f33",2301:"2b3ca9e8",2311:"45ffaac0",2347:"6ece5c56",2358:"70580274",2369:"43598dd6",2400:"68bd2d96",2421:"0c7d42fe",2459:"6df76c9d",2491:"45e28f07",2589:"de97890f",2592:"0fd15954",2596:"7d27119c",2600:"48d425a0",2605:"6e77de51",2634:"e0be6be1",2674:"b6a13eda",2676:"9f1d1734",2720:"322bc4b8",2743:"06c86712",2784:"101a90d5",2830:"871dcece",2858:"0007f100",2862:"661fb3a8",2917:"eea21b14",2935:"d45e3652",2952:"31bb42be",2958:"ea705c74",2960:"1c63ec79",2962:"48924c16",2964:"ea8060e2",2965:"de613831",2998:"4d52e402",3088:"3f57a286",3126:"5edf73c4",3137:"8d5db1a9",3177:"9d430517",3195:"39a52354",3196:"09da66bc",3308:"5b5ca3da",3332:"55388635",3343:"3aa583e2",3355:"abbb7da4",3359:"fbc54514",3382:"116eca1b",3419:"11f1af27",3449:"6f5afd18",3457:"7f5ab153",3460:"20ea55e4",3468:"6ad10b96",3507:"1c973b5a",3565:"82f09992",3576:"31f38c8d",3585:"c6af0b12",3610:"e2729820",3613:"c82c5b5b",3642:"67b2a230",3672:"5b731e8a",3693:"5b8587bb",3701:"bfee7348",3712:"54104957",3723:"5f092d25",3765:"77166e71",3781:"ac73da7f",3811:"841208ca",3820:"920d2cd9",3955:"ba5e1374",3962:"70e7214b",4e3:"1a9c939a",4017:"ef617e12",4021:"c0211075",4032:"81deafd2",4053:"5238c789",4054:"5d51fb83",4086:"972829be",4103:"d0f77da4",4116:"18a539ee",4122:"2da3d499",4124:"86c008fb",4224:"d02d6cc1",4225:"3402cbae",4253:"9e057df3",4279:"71f37a5e",4299:"5dab1277",4324:"fca6fc61",4330:"be427580",4366:"9376b16b",4368:"da5bc172",4393:"b3ead152",4422:"6704a06c",4438:"92665f44",4474:"64938b3f",4485:"e9fc4b1c",4513:"221c7e6d",4548:"2fee95fb",4565:"53f40c9c",4619:"49370dc4",4620:"dc35b3f9",4664:"2c80a6e5",4671:"702ab7f9",4690:"563b4cd6",4706:"fbab3a9d",4716:"1fba9352",4761:"de27ac75",4762:"5a5417be",4773:"993bc61e",4779:"dcda4ae0",4780:"252983b3",4803:"52e92924",4805:"5d3e0f7f",4807:"50b4e40c",4827:"e5c176a5",4840:"064a3472",4843:"21082f6b",4876:"acd35b74",4884:"9ddbd2d1",4893:"5b766b08",4919:"81674c15",4954:"82b76686",4955:"3168611a",4978:"52fa3839",4981:"b7b1e3e0",5e3:"a539b294",5011:"06ab14fb",5049:"adf1fcbf",5083:"90069866",5091:"a282a486",5099:"f6cb8ea8",5138:"968ca243",5170:"e7a8c20e",5180:"76971fab",5198:"4bece173",5235:"e39ea11f",5281:"a312a130",5282:"882f2590",5316:"d594a844",5356:"3813694a",5362:"0fa1a14b",5409:"8794de2a",5473:"8918d844",5511:"6bfc22c0",5515:"99b4e529",5518:"ae550287",5526:"b1d01353",5547:"0caaaeb8",5558:"ea970a87",5619:"38b9cf53",5646:"6e04135c",5675:"2b72d61e",5730:"e118ef3e",5738:"554c4783",5747:"36f5b217",5761:"8417400f",5762:"6c7f6118",5766:"4dfec083",5779:"54300e03",5830:"2c8a41a6",5832:"7c7ff7e3",5856:"24725f2e",5884:"b515bb0f",5923:"42dc98ea",5962:"e4451793",5981:"dc71c1b6",6009:"c85f1b45",6053:"1d79c6ae",6086:"c64b8dee",6088:"58680537",6095:"a683b422",6123:"827b3b19",6145:"52420cde",6151:"7f0623e3",6158:"44507640",6192:"f81fee58",6205:"edc2fc06",6209:"4541130b",6219:"0e26beae",6253:"dac2cd6d",6266:"19cc57bd",6337:"142ca450",6361:"e7db4435",6364:"a2e3b42d",6369:"9890d336",6408:"81035d33",6427:"2af07bda",6473:"6d0f76ea",6481:"9d786417",6487:"75de77e7",6523:"a65e41a7",6537:"512b4df8",6556:"076729ae",6579:"e1cf7b88",6599:"599d329c",6621:"69c85a33",6628:"3c6fd15a",6681:"abe2da8e",6700:"eee0aecd",6714:"56296377",6729:"03cabaec",6730:"6147159c",6766:"ab787787",6874:"f5b2adb7",6894:"50e431dd",6912:"9222037b",6918:"a43926d8",6924:"d0beb915",6925:"c14947dc",6931:"a6253d51",6961:"ff156576",6972:"bffa68d0",6981:"85adf6e2",6984:"41e0e0e1",6986:"a2553195",7035:"fd9375e2",7041:"a7a587eb",7042:"8e115802",7045:"c66c8d29",7107:"db99bd1a",7110:"ae341e96",7116:"f56ce99b",7141:"02e8c648",7143:"12658908",7146:"6d20fea0",7200:"8a60f2ff",7248:"d9018415",7258:"c73b3d9d",7321:"0e9e02ad",7326:"c3b07156",7341:"206f1033",7362:"572d4fd6",7371:"421fe189",7373:"d957599d",7382:"cca2946f",7471:"ef16c98f",7483:"2f77f2a1",7492:"8c3dea08",7542:"df1707bf",7544:"1e08f94f",7575:"bd94c17c",7591:"a495c84c",7696:"bf2cd8fc",7735:"3cb139c7",7757:"fa09855a",7800:"2efbceef",7846:"dc4d6da3",7858:"1a554faa",7868:"ff2fe3de",7906:"00df55b4",7924:"89953d13",7938:"5824a63a",7940:"d01ca2bb",7942:"e5046e45",8023:"a1750297",8025:"e7a2a4f7",8028:"a3ed74ef",8042:"2f241f7d",8055:"db17b7db",8059:"0f6f610e",8060:"19fef1a9",8087:"7b918e26",8093:"67a39e10",8100:"9dcce287",8107:"b3a00efb",8112:"d95c0503",8158:"5d3c0904",8166:"63dc4aba",8173:"f74e87f3",8177:"7ca61dac",8194:"c594d384",8260:"04f40872",8267:"0352807a",8309:"c54a1418",8313:"dc9f16bf",8327:"7cb47364",8330:"8ec984fe",8350:"cb8b8de8",8357:"36a1f25d",8372:"ec3d26d8",8401:"66024bca",8414:"1913b948",8457:"e51dcb3d",8470:"53c389e0",8478:"dd5df81f",8483:"ade72d33",8526:"bdbe52f0",8542:"1e186d4a",8548:"7616f868",8581:"5cadb39b",8588:"978dd91e",8607:"dbd64ae9",8621:"8c69c63d",8628:"0fc3f62b",8633:"a4bb9e2a",8688:"99c1a8d5",8703:"be2bef33",8714:"89f94980",8718:"b16c1c96",8722:"dcd10efb",8735:"ba066590",8798:"b23423d9",8868:"7d8ac123",8871:"63d9cb43",8873:"a0c1a1bd",8913:"1f670d9b",8919:"0b8eb41a",8933:"e1257188",8945:"3c3c26bd",8950:"324ec300",8997:"b56ac654",9008:"b7e599f7",9013:"3b18f36b",9026:"25345306",9032:"64b940b8",9040:"ca62b12f",9062:"24eb6a09",9092:"c87f773f",9096:"3878a6d8",9097:"140e06b8",9127:"ffb0bc4a",9158:"bb8492ea",9219:"0cb2f4db",9227:"578cf119",9249:"50e7520e",9255:"74119e9a",9262:"1e1e0a39",9271:"5828a06b",9282:"f893e966",9336:"bd4657d8",9368:"e1138f0b",9439:"6f6d22dc",9441:"785d30b6",9445:"6a0331a4",9454:"2bdba581",9472:"76a2b02b",9581:"a01184e8",9594:"5698427e",9606:"d52d4095",9624:"4a75d253",9661:"09caf28c",9717:"f299a405",9742:"99a98fa7",9775:"830cce27",9778:"a389bf5f",9793:"4a24ebcb",9798:"700a4ca5",9810:"5fa26c20",9828:"d65a31dd",9866:"6c07b693",9870:"4b2d0413",9917:"8a82af14",9949:"6cf2b1e6"}[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,c)=>Object.prototype.hasOwnProperty.call(e,c),b={},r.l=(e,c,a,f)=>{if(b[e])b[e].push(c);else{var d,t;if(void 0!==a)for(var o=document.getElementsByTagName("script"),n=0;n{d.onerror=d.onload=null,clearTimeout(l);var f=b[e];if(delete b[e],d.parentNode&&d.parentNode.removeChild(d),f&&f.forEach((e=>e(a))),c)return c(a)},l=setTimeout(u.bind(null,void 0,{type:"timeout",target:d}),12e4);d.onerror=u.bind(null,d.onerror),d.onload=u.bind(null,d.onload),t&&document.head.appendChild(d)}},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:"8873",17896441:"8401",18100524:"1264",23794275:"1776",38317547:"4225",61595218:"9775",78619623:"6209",85339969:"7141",95073452:"5962",95576100:"1898",96877411:"5526",e196b408:"2","1e138b9d":"40",a27ea030:"68","1e7fe27e":"79","58d52345":"81","5e352ef4":"104","8f967659":"109",c7e7ae18:"152","652c74f1":"211","4bdafdff":"222","767c28af":"229",beccb025:"247","5dde70bf":"288",f2710c27:"321",f309eabc:"324","085c135f":"362","68b7d615":"436","2bbfc5d5":"458",a3a193a6:"464",b5d32d98:"481",a30fd8ca:"501","08fe23a4":"514",c007fb39:"521","7f74c501":"540",b35d1284:"552","89ed63c8":"573",a9bc4f03:"629",ac8293fa:"630",bb5ef1b7:"651",b6722b03:"663",f7c03581:"770",e126d786:"776",a13f3cdc:"835","606959d6":"862","0e5befdb":"932","48fde361":"958","528fe65e":"1027",eca0cf35:"1039",a27f6be0:"1062",b2d9540a:"1084","4dfeb783":"1126",eaa287f0:"1133",c4d37b36:"1141","6c14a231":"1188","6d89025c":"1190",c10d4a63:"1235","1edb88e5":"1245","02c5a8b1":"1289",c7a4caa1:"1308","4f59166d":"1340","2e25c87f":"1345","1ca907c0":"1431","4d68b066":"1443",d9523c62:"1465",b26a5b84:"1481","8f7fa040":"1505",fa41c0e9:"1538","9bd507da":"1565","843ebfb4":"1585","3c86ad25":"1587","4dd5816e":"1604","21cde469":"1653",d8ff000f:"1661","2f36012a":"1674","2fc68ddc":"1763",e39283a8:"1766",b4657038:"1886",aa5b6080:"1894","55c77f1e":"1930","23a8ac29":"1950",c3701568:"1968","7ade2db5":"1975","27258a7d":"1985","9000b231":"2032",common:"2076",b69ed219:"2089","1ea13486":"2112",cd25a595:"2113",e7ffb4b4:"2119","1a4e3797":"2138","4d049718":"2156","07666c14":"2174",dc9a99e0:"2187","94ecc552":"2197","1aa05129":"2207","0db959c8":"2227","8b6bafea":"2230","3d2d0a86":"2235",c275698c:"2248","5ececfab":"2275",a9125b44:"2301",bfe5398f:"2311","5e21a9be":"2347",aa675676:"2358","079b0d3e":"2369","7ee46e43":"2400",f4e1d1ba:"2421","25d4129e":"2459","1e2c5f46":"2491","4f4b6633":"2589","8f7abfe1":"2592","1d20a4b3":"2596",e7672013:"2600",c5fa393d:"2605",c4f5d8e4:"2634",ca36df4d:"2674","5ec7a7fe":"2676","4c5bf49d":"2720","01fe3043":"2743","69f2ab1f":"2784",b9ea999a:"2830","29cf2ad6":"2858","7e507331":"2862","36ddade1":"2917","0df2ba32":"2935",bcc01c83:"2952",db6a6f31:"2958","64536e1a":"2960","1f5af0f2":"2962","23f642f2":"2964","1af245cd":"2965",ae0a12ed:"2998","242d99d9":"3088","4aab8b8c":"3126","4f6c3156":"3137",cc1f18af:"3177","7d4976a8":"3195",bcb6471f:"3196","9953ecde":"3308","71a56230":"3332",b5d0ac54:"3343","5fa4a5b6":"3355",e91daeb9:"3359","21a7a3b0":"3382","756c6ac7":"3419",e617c97b:"3449","5e457383":"3457","1891fd2b":"3460","68e30702":"3468","77cdcd82":"3507","3a3e6a89":"3565","82395e72":"3576","3f944aba":"3585","579cc8d4":"3610","22e1e32f":"3613","263ebc7a":"3642",b103c05a:"3672","5a9b411c":"3693","8d81badd":"3701",d49884c9:"3712","1428bdad":"3723","0343976d":"3765",b7442939:"3781","4445fe20":"3811","24aca886":"3820",aba5bf07:"3955","16565e6a":"3962",ce95b17c:"4000","9073923c":"4017","03abab96":"4021","56279b5e":"4032","78da31a1":"4053","20540af3":"4054","6b4e0fb4":"4086",d07ad772:"4103",cddcd4e6:"4116","5ffc8074":"4122",e8a97ac3:"4124",a16ee953:"4224","87089bce":"4253","610e7425":"4279","5b80a12a":"4299",e806c7bf:"4324","65b8d1d1":"4330","16017aa6":"4366","56af72f6":"4368","27e787ca":"4393","18d6c9c9":"4422","7afb60b1":"4438",a7159008:"4474","59b1a96c":"4485",d3540d59:"4513",d8037f4c:"4548","7b54f5d5":"4565",a228ae9b:"4619","05fed6b1":"4620",e4c5fdc3:"4664","1d703573":"4671",f48e2589:"4690","2f46a9d9":"4706",ba7653ad:"4716","1e6ec01e":"4761","232afa3a":"4762","5945e8b0":"4773",a320b509:"4779","332827b4":"4780","06c02cc7":"4803","6efd6ec9":"4805",d4446569:"4807","03c886f6":"4827",e688cd7e:"4840","4e1a0951":"4843",a0bf4a5f:"4876","74383bd8":"4884","9f0ecd2e":"4893",aa52484c:"4919","26a27afb":"4954",b6a6a31f:"4955",e5d0e3cb:"4978","4e73bd72":"4981","2d02c83c":"5000",c953ec08:"5011",bdb33130:"5049","73ccb1b9":"5083","05e8cfc0":"5091","1b1927f4":"5099",b4aea2ce:"5138","6c8ff36a":"5170","366cfce3":"5180","143f7888":"5198","6fe30f11":"5235",cd699560:"5281",eec7caa6:"5282",c8bdc4df:"5316","60d99771":"5356","323a980a":"5362","38cf1c7a":"5409","3b58261a":"5473",fa1dd05c:"5511",cc08685c:"5515",e347e63a:"5518","565a5567":"5547","3d0eb74d":"5558","7bf967bc":"5619","612b773e":"5646","5285d58e":"5675","32e2b5e3":"5730",eb333c39:"5738",b370b50c:"5747","0fad1f8b":"5761","6c124661":"5762","8e97f284":"5766","85c72337":"5779",f90c5a21:"5830",bb9fe7c3:"5832","90e0b7fd":"5856",e29eb381:"5884","27b414e3":"5923","0d7bb119":"5981","8299d165":"6009","17cca601":"6053","136c1ee9":"6086","13b4aeb1":"6088","741df2ae":"6095",a2d3d8d2:"6123","2355609d":"6145",c933a311:"6151","0fd21208":"6158",c69dda99:"6192","4ed8ec4c":"6205",a91c1a62:"6219","999289d8":"6253",be1f0304:"6266",a28aff23:"6337",d74b5642:"6361",d4a334ea:"6364","96fc29fc":"6369","107b7a36":"6408",b42f5805:"6427","107d11ee":"6473","2014e4e3":"6481","8223875c":"6487","8bf32d27":"6523","4a2da18c":"6537",d6b4b60c:"6556",d7067606:"6579","029c6d75":"6599","61c7d915":"6621",b94a1068:"6628","9bbf4a9a":"6681","394f3211":"6700","2b6906c9":"6714","15a79915":"6729","6ad31330":"6730","54ca8693":"6766",bda39da3:"6874","504e6c2d":"6894",c1fe0282:"6912","32562f03":"6918","617523b3":"6924","07623f9a":"6925","28c12eaf":"6931","400ddbbb":"6961","31b4e903":"6972",ece9cf29:"6981","7e63a40e":"6984","077a13b8":"6986","72d0dc3a":"7035","607daa94":"7041","12d3ef9e":"7042","72be5fd7":"7045","04610919":"7107","9749ab4a":"7110","4194805f":"7116",e6858589:"7143","5d95c2e4":"7146","1520c72c":"7200",e38ecde0:"7248",f9511b3d:"7258","26662da3":"7321","673df5d6":"7326",f07f4757:"7341","766e1cc8":"7362",c6df2ddc:"7371",f5b0a435:"7373","822cd419":"7382","0a57d896":"7471","30940d42":"7483",cc1c02fe:"7492",a264d631:"7542","9664ee55":"7544","8913b51a":"7575","1f5e9707":"7591","9206a32f":"7696","54c144e4":"7735","380575ae":"7757","623b6c78":"7800","947f2c39":"7846","89cae3a7":"7858","8e2662b8":"7868",b06c439f:"7906",d589d3a7:"7924","51b7da58":"7938",b0ed7ea5:"7940","354a9b78":"7942","15b5a907":"8023",dbf2bcb3:"8025","0db009bb":"8028","29a6c1ba":"8042",e1b8bb84:"8055",fe153c07:"8059",dab32d56:"8060","6a8c9872":"8087",a23a5b68:"8093","3b486936":"8100",e45c611c:"8107","0cb7e976":"8112","471c3e37":"8166",e68b092b:"8173",cf877cff:"8177","950394a4":"8194",e63ebe23:"8260","50122f86":"8267",a95c9e82:"8309","379bfe51":"8313",f9af357c:"8327",d62b7e4c:"8330","6c4340be":"8350",aebf35b6:"8357","57f5c28c":"8372",c0fa6485:"8414","509d2004":"8457","1ba75d10":"8470","2d4548df":"8478",acbaac14:"8483",b8487569:"8526",b9d6d6e5:"8542","346bcb92":"8548","935f2afb":"8581",a3c6f073:"8588",c1068675:"8607","4a07aaf0":"8621","5881f7ec":"8628","07c49ebd":"8633","4d00e03a":"8688",cb01db44:"8703","1be78505":"8714","75cc8326":"8718","64947e00":"8722","2917b31e":"8735","6cfcfcfb":"8798",f9063551:"8868","5fb37434":"8871",bf2a5963:"8919",f94b062c:"8933",e2e51976:"8945",ed0c0463:"8950","4a060504":"8997","24ac61c7":"9008","9d9f8394":"9013",bd2c4a98:"9026","21637dff":"9032",e5d7b215:"9040",caa79efa:"9062","2ef99682":"9092","7b417fb4":"9096","102de343":"9097","2b26025e":"9127","8c95fc16":"9158","36b1b0cc":"9219","7c27e34c":"9227",c329487f:"9249","0ef60658":"9255","9279cea7":"9262","7810a993":"9271",d4c8693b:"9282","5d7590c2":"9336","2830ce57":"9368","8f951ce3":"9439",a55b0daf:"9441","6c6ce37c":"9445","5bc7272e":"9454","4c7f7507":"9472","4f30448a":"9581",c32ff706:"9594","5792f9ba":"9606","2e301473":"9624",cd30f404:"9661","976f6afc":"9717","820db038":"9742","9d336ee4":"9778","0370fbfb":"9793","58e6b30f":"9798","859fcda7":"9810",d6188fd4:"9828",a99e9943:"9866","7515d7ec":"9870","91e22cb6":"9917",a1e3d512:"9949"}[e]||e,r.p+r.u(e)},(()=>{var e={5354:0,1869:0};r.f.j=(c,a)=>{var b=r.o(e,c)?e[c]:void 0;if(0!==b)if(b)a.push(b[2]);else if(/^(1869|5354)$/.test(c))e[c]=0;else{var f=new Promise(((a,f)=>b=e[c]=[a,f]));a.push(b[2]=f);var d=r.p+r.u(c),t=new Error;r.l(d,(a=>{if(r.o(e,c)&&(0!==(b=e[c])&&(e[c]=void 0),b)){var f=a&&("load"===a.type?"missing":a.type),d=a&&a.target&&a.target.src;t.message="Loading chunk "+c+" failed.\n("+f+": "+d+")",t.name="ChunkLoadError",t.type=f,t.request=d,b[1](t)}}),"chunk-"+c,c)}},r.O.j=c=>0===e[c];var c=(c,a)=>{var b,f,d=a[0],t=a[1],o=a[2],n=0;if(d.some((c=>0!==e[c]))){for(b in t)r.o(t,b)&&(r.m[b]=t[b]);if(o)var i=o(r)}for(c&&c(a);n{"use strict";var e,c,a,d,b={},f={};function r(e){var c=f[e];if(void 0!==c)return c.exports;var a=f[e]={exports:{}};return b[e].call(a.exports,a,a.exports,r),a.exports}r.m=b,e=[],r.O=(c,a,d,b)=>{if(!a){var f=1/0;for(i=0;i=b)&&Object.keys(r.O).every((e=>r.O[e](a[o])))?a.splice(o--,1):(t=!1,b0&&e[i-1][2]>b;i--)e[i]=e[i-1];e[i]=[a,d,b]},r.n=e=>{var c=e&&e.__esModule?()=>e.default:()=>e;return r.d(c,{a:c}),c},a=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(e,d){if(1&d&&(e=this(e)),8&d)return e;if("object"==typeof e&&e){if(4&d&&e.__esModule)return e;if(16&d&&"function"==typeof e.then)return e}var b=Object.create(null);r.r(b);var f={};c=c||[null,a({}),a([]),a(a)];for(var t=2&d&&e;"object"==typeof t&&!~c.indexOf(t);t=a(t))Object.getOwnPropertyNames(t).forEach((c=>f[c]=()=>e[c]));return f.default=()=>e,r.d(b,f),b},r.d=(e,c)=>{for(var a in c)r.o(c,a)&&!r.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:c[a]})},r.f={},r.e=e=>Promise.all(Object.keys(r.f).reduce(((c,a)=>(r.f[a](e,c),c)),[])),r.u=e=>"assets/js/"+({2:"e196b408",40:"1e138b9d",68:"a27ea030",79:"1e7fe27e",81:"58d52345",104:"5e352ef4",109:"8f967659",152:"c7e7ae18",211:"652c74f1",222:"4bdafdff",229:"767c28af",247:"beccb025",288:"5dde70bf",321:"f2710c27",324:"f309eabc",362:"085c135f",436:"68b7d615",458:"2bbfc5d5",464:"a3a193a6",481:"b5d32d98",501:"a30fd8ca",514:"08fe23a4",521:"c007fb39",540:"7f74c501",552:"b35d1284",573:"89ed63c8",629:"a9bc4f03",630:"ac8293fa",651:"bb5ef1b7",663:"b6722b03",770:"f7c03581",776:"e126d786",835:"a13f3cdc",862:"606959d6",932:"0e5befdb",958:"48fde361",1027:"528fe65e",1039:"eca0cf35",1062:"a27f6be0",1084:"b2d9540a",1126:"4dfeb783",1133:"eaa287f0",1141:"c4d37b36",1188:"6c14a231",1190:"6d89025c",1235:"c10d4a63",1245:"1edb88e5",1264:"18100524",1289:"02c5a8b1",1308:"c7a4caa1",1340:"4f59166d",1345:"2e25c87f",1431:"1ca907c0",1443:"4d68b066",1465:"d9523c62",1481:"b26a5b84",1505:"8f7fa040",1538:"fa41c0e9",1565:"9bd507da",1585:"843ebfb4",1587:"3c86ad25",1604:"4dd5816e",1653:"21cde469",1661:"d8ff000f",1674:"2f36012a",1763:"2fc68ddc",1766:"e39283a8",1776:"23794275",1886:"b4657038",1894:"aa5b6080",1898:"95576100",1930:"55c77f1e",1950:"23a8ac29",1968:"c3701568",1975:"7ade2db5",1985:"27258a7d",2032:"9000b231",2076:"common",2089:"b69ed219",2112:"1ea13486",2113:"cd25a595",2119:"e7ffb4b4",2138:"1a4e3797",2156:"4d049718",2174:"07666c14",2187:"dc9a99e0",2197:"94ecc552",2207:"1aa05129",2227:"0db959c8",2230:"8b6bafea",2235:"3d2d0a86",2248:"c275698c",2275:"5ececfab",2301:"a9125b44",2311:"bfe5398f",2347:"5e21a9be",2358:"aa675676",2369:"079b0d3e",2400:"7ee46e43",2421:"f4e1d1ba",2459:"25d4129e",2491:"1e2c5f46",2589:"4f4b6633",2592:"8f7abfe1",2596:"1d20a4b3",2600:"e7672013",2605:"c5fa393d",2634:"c4f5d8e4",2674:"ca36df4d",2676:"5ec7a7fe",2720:"4c5bf49d",2743:"01fe3043",2784:"69f2ab1f",2830:"b9ea999a",2858:"29cf2ad6",2862:"7e507331",2917:"36ddade1",2935:"0df2ba32",2952:"bcc01c83",2958:"db6a6f31",2960:"64536e1a",2962:"1f5af0f2",2964:"23f642f2",2965:"1af245cd",2998:"ae0a12ed",3088:"242d99d9",3126:"4aab8b8c",3137:"4f6c3156",3177:"cc1f18af",3195:"7d4976a8",3196:"bcb6471f",3308:"9953ecde",3332:"71a56230",3343:"b5d0ac54",3355:"5fa4a5b6",3359:"e91daeb9",3382:"21a7a3b0",3419:"756c6ac7",3449:"e617c97b",3457:"5e457383",3460:"1891fd2b",3468:"68e30702",3507:"77cdcd82",3565:"3a3e6a89",3576:"82395e72",3585:"3f944aba",3610:"579cc8d4",3613:"22e1e32f",3642:"263ebc7a",3672:"b103c05a",3693:"5a9b411c",3701:"8d81badd",3712:"d49884c9",3723:"1428bdad",3765:"0343976d",3781:"b7442939",3811:"4445fe20",3820:"24aca886",3955:"aba5bf07",3962:"16565e6a",4e3:"ce95b17c",4017:"9073923c",4021:"03abab96",4032:"56279b5e",4053:"78da31a1",4054:"20540af3",4086:"6b4e0fb4",4103:"d07ad772",4116:"cddcd4e6",4122:"5ffc8074",4124:"e8a97ac3",4224:"a16ee953",4225:"38317547",4253:"87089bce",4279:"610e7425",4299:"5b80a12a",4324:"e806c7bf",4330:"65b8d1d1",4366:"16017aa6",4368:"56af72f6",4393:"27e787ca",4422:"18d6c9c9",4438:"7afb60b1",4474:"a7159008",4485:"59b1a96c",4513:"d3540d59",4548:"d8037f4c",4565:"7b54f5d5",4619:"a228ae9b",4620:"05fed6b1",4664:"e4c5fdc3",4671:"1d703573",4690:"f48e2589",4706:"2f46a9d9",4716:"ba7653ad",4761:"1e6ec01e",4762:"232afa3a",4773:"5945e8b0",4779:"a320b509",4780:"332827b4",4803:"06c02cc7",4805:"6efd6ec9",4807:"d4446569",4827:"03c886f6",4840:"e688cd7e",4843:"4e1a0951",4876:"a0bf4a5f",4884:"74383bd8",4893:"9f0ecd2e",4919:"aa52484c",4954:"26a27afb",4955:"b6a6a31f",4978:"e5d0e3cb",4981:"4e73bd72",5e3:"2d02c83c",5011:"c953ec08",5049:"bdb33130",5083:"73ccb1b9",5091:"05e8cfc0",5099:"1b1927f4",5138:"b4aea2ce",5170:"6c8ff36a",5180:"366cfce3",5198:"143f7888",5235:"6fe30f11",5281:"cd699560",5282:"eec7caa6",5316:"c8bdc4df",5356:"60d99771",5362:"323a980a",5409:"38cf1c7a",5473:"3b58261a",5511:"fa1dd05c",5515:"cc08685c",5518:"e347e63a",5526:"96877411",5547:"565a5567",5558:"3d0eb74d",5619:"7bf967bc",5646:"612b773e",5675:"5285d58e",5730:"32e2b5e3",5738:"eb333c39",5747:"b370b50c",5761:"0fad1f8b",5762:"6c124661",5766:"8e97f284",5779:"85c72337",5830:"f90c5a21",5832:"bb9fe7c3",5856:"90e0b7fd",5884:"e29eb381",5923:"27b414e3",5962:"95073452",5981:"0d7bb119",6009:"8299d165",6053:"17cca601",6086:"136c1ee9",6088:"13b4aeb1",6095:"741df2ae",6123:"a2d3d8d2",6145:"2355609d",6151:"c933a311",6158:"0fd21208",6192:"c69dda99",6205:"4ed8ec4c",6209:"78619623",6219:"a91c1a62",6253:"999289d8",6266:"be1f0304",6337:"a28aff23",6361:"d74b5642",6364:"d4a334ea",6369:"96fc29fc",6408:"107b7a36",6427:"b42f5805",6473:"107d11ee",6481:"2014e4e3",6487:"8223875c",6523:"8bf32d27",6537:"4a2da18c",6556:"d6b4b60c",6579:"d7067606",6599:"029c6d75",6621:"61c7d915",6628:"b94a1068",6681:"9bbf4a9a",6700:"394f3211",6714:"2b6906c9",6729:"15a79915",6730:"6ad31330",6766:"54ca8693",6874:"bda39da3",6894:"504e6c2d",6912:"c1fe0282",6918:"32562f03",6924:"617523b3",6925:"07623f9a",6931:"28c12eaf",6961:"400ddbbb",6972:"31b4e903",6981:"ece9cf29",6984:"7e63a40e",6986:"077a13b8",7035:"72d0dc3a",7041:"607daa94",7042:"12d3ef9e",7045:"72be5fd7",7107:"04610919",7110:"9749ab4a",7116:"4194805f",7141:"85339969",7143:"e6858589",7146:"5d95c2e4",7200:"1520c72c",7248:"e38ecde0",7258:"f9511b3d",7321:"26662da3",7326:"673df5d6",7341:"f07f4757",7362:"766e1cc8",7371:"c6df2ddc",7373:"f5b0a435",7382:"822cd419",7471:"0a57d896",7483:"30940d42",7492:"cc1c02fe",7542:"a264d631",7544:"9664ee55",7575:"8913b51a",7591:"1f5e9707",7696:"9206a32f",7735:"54c144e4",7757:"380575ae",7800:"623b6c78",7846:"947f2c39",7858:"89cae3a7",7868:"8e2662b8",7906:"b06c439f",7924:"d589d3a7",7938:"51b7da58",7940:"b0ed7ea5",7942:"354a9b78",8023:"15b5a907",8025:"dbf2bcb3",8028:"0db009bb",8042:"29a6c1ba",8055:"e1b8bb84",8059:"fe153c07",8060:"dab32d56",8087:"6a8c9872",8093:"a23a5b68",8100:"3b486936",8107:"e45c611c",8112:"0cb7e976",8166:"471c3e37",8173:"e68b092b",8177:"cf877cff",8194:"950394a4",8260:"e63ebe23",8267:"50122f86",8309:"a95c9e82",8313:"379bfe51",8327:"f9af357c",8330:"d62b7e4c",8350:"6c4340be",8357:"aebf35b6",8372:"57f5c28c",8401:"17896441",8414:"c0fa6485",8457:"509d2004",8470:"1ba75d10",8478:"2d4548df",8483:"acbaac14",8526:"b8487569",8542:"b9d6d6e5",8548:"346bcb92",8581:"935f2afb",8588:"a3c6f073",8607:"c1068675",8621:"4a07aaf0",8628:"5881f7ec",8633:"07c49ebd",8688:"4d00e03a",8703:"cb01db44",8714:"1be78505",8718:"75cc8326",8722:"64947e00",8735:"2917b31e",8798:"6cfcfcfb",8868:"f9063551",8871:"5fb37434",8873:"17518879",8919:"bf2a5963",8933:"f94b062c",8945:"e2e51976",8950:"ed0c0463",8997:"4a060504",9008:"24ac61c7",9013:"9d9f8394",9026:"bd2c4a98",9032:"21637dff",9040:"e5d7b215",9062:"caa79efa",9092:"2ef99682",9096:"7b417fb4",9097:"102de343",9127:"2b26025e",9158:"8c95fc16",9219:"36b1b0cc",9227:"7c27e34c",9249:"c329487f",9255:"0ef60658",9262:"9279cea7",9271:"7810a993",9282:"d4c8693b",9336:"5d7590c2",9368:"2830ce57",9439:"8f951ce3",9441:"a55b0daf",9445:"6c6ce37c",9454:"5bc7272e",9472:"4c7f7507",9581:"4f30448a",9594:"c32ff706",9606:"5792f9ba",9624:"2e301473",9661:"cd30f404",9717:"976f6afc",9742:"820db038",9775:"61595218",9778:"9d336ee4",9793:"0370fbfb",9798:"58e6b30f",9810:"859fcda7",9828:"d6188fd4",9866:"a99e9943",9870:"7515d7ec",9917:"91e22cb6",9949:"a1e3d512"}[e]||e)+"."+{2:"c6be2aa7",40:"af88d16b",68:"dc26afa1",79:"46ea8ff8",81:"0df60a2d",104:"0bebc6a8",109:"d7936e3d",152:"ee32871a",211:"8f6d89ec",222:"a73df832",229:"d9ac76d3",247:"9437bedc",288:"477b054f",321:"94ebd814",324:"81e87848",362:"41ba6b03",416:"85e975e8",436:"06b7671d",458:"fe37f321",464:"b4dee0e0",481:"f05b0f6c",501:"1c3c185f",514:"5847e977",521:"4066ed8c",540:"1de07200",552:"8a45607f",573:"3a63ee5a",629:"79e0d8ad",630:"0add98f9",651:"9bb649c8",663:"72cf7e0e",770:"ab9ca9fa",776:"b4750660",835:"bce6936a",862:"cd0e5d4c",932:"a35881e8",958:"156e0f5a",1027:"8ac08875",1039:"511fc0e7",1062:"d4e018f5",1084:"2e9ca6f7",1126:"89bb581b",1133:"534b794e",1141:"ec117dcc",1188:"cd87becb",1190:"8c59f230",1235:"220b95fc",1245:"0bec25f2",1264:"0c790315",1289:"700b0e1a",1308:"8813fc32",1340:"b3fa1d46",1345:"4ba0ae27",1431:"0d0f4c41",1443:"60b726ef",1465:"a8413bae",1481:"a3068e3f",1505:"88306093",1538:"957dcfcd",1565:"346f47b6",1585:"2328701a",1587:"272dcc24",1604:"64ab8a1d",1653:"ef6b9adb",1661:"23ad97e0",1674:"9ea7bba6",1763:"2591b067",1766:"70a0c24c",1774:"9b58a5d2",1776:"b58c4864",1886:"7c76f1b3",1894:"202b05d1",1898:"0f56eb6d",1930:"e0e09ff5",1950:"a124ce1b",1968:"cab1ce33",1975:"bbfffb1d",1985:"04470269",2032:"13a2c4ab",2076:"8b81e25b",2089:"fb526318",2112:"63f904ea",2113:"98e47423",2119:"789e1741",2138:"f477ed0f",2156:"c6fcb28d",2174:"632db5d1",2187:"c8144eaf",2197:"3b2f4d51",2207:"c022cfc4",2227:"87e96419",2230:"cd594754",2235:"aa21ee01",2248:"e823393f",2275:"3e198c19",2301:"76fd5a69",2311:"26707152",2347:"74ae7e21",2358:"65e35c40",2369:"8f199a77",2400:"29e7eea9",2421:"8b13eb66",2459:"68e7b119",2491:"65b9961d",2589:"efc72abb",2592:"e7a52f5f",2596:"4bdc2a57",2600:"44846702",2605:"e1f9c3bd",2634:"e0be6be1",2674:"61047158",2676:"6f344f93",2720:"21adcfe4",2743:"2692f6f5",2784:"1faf5012",2830:"bd76e3cd",2858:"e5258851",2862:"7852fba8",2917:"f83468ca",2935:"40734af9",2952:"2bd73636",2958:"15ffc30c",2960:"c293a5d2",2962:"7701c5a6",2964:"1564dfe4",2965:"1a292e94",2998:"dd201707",3088:"76f7b35a",3126:"ff6f0690",3137:"c0232592",3177:"cf44e18c",3195:"39a52354",3196:"da58a603",3308:"a070338d",3332:"13b5bfe0",3343:"f18e7f3c",3355:"f2b014e5",3359:"8e7131fe",3382:"1330d704",3419:"453122bd",3449:"1accdd02",3457:"d7e58f2f",3460:"a8e3c91b",3468:"2c897d24",3507:"c070a849",3565:"777b0fc3",3576:"49c98b08",3585:"b52fcb1d",3610:"33781386",3613:"08dbebdc",3642:"12eb452f",3672:"7389b7f1",3693:"e5c6ed99",3701:"fe9f30d2",3712:"270e6dca",3723:"e9676a5b",3765:"a935053c",3781:"e9f19ed1",3811:"9022a165",3820:"5ba7e1af",3955:"0d27af80",3962:"7840e1d0",4e3:"086e4223",4017:"de36f167",4021:"a07ccaca",4032:"29c4d3ad",4053:"7208e28d",4054:"0917bd96",4086:"af536444",4103:"e7609360",4116:"37e96033",4122:"a35bb01d",4124:"0a231a8d",4224:"29db8d4b",4225:"9620f8ef",4253:"a9173e85",4279:"8f1eebec",4299:"472efb90",4324:"6fd79788",4330:"2e0aa238",4366:"eadedf44",4368:"73430305",4393:"b3ead152",4422:"e70b6848",4438:"e108e213",4474:"64938b3f",4485:"d84d6050",4513:"fa61907b",4548:"c3b97d24",4565:"c9905422",4619:"2a435235",4620:"d73b7c21",4664:"c11dcebd",4671:"eba89edd",4690:"fe03d88b",4706:"195005ee",4716:"201e2661",4761:"ac95ff0a",4762:"11ff0b56",4773:"b053de15",4779:"567f3680",4780:"8809e5b5",4803:"9e169703",4805:"45f89857",4807:"3cbc548f",4827:"579f399b",4840:"328d42a5",4843:"99886c87",4876:"edd3ca79",4884:"fc1132ac",4893:"f474bd30",4919:"1be28e63",4954:"2468a3db",4955:"c449286c",4978:"89229e6e",4981:"9eff4f50",5e3:"1450cf33",5011:"be3c3152",5049:"423bf6c8",5083:"530685ad",5091:"b3c9b9a7",5099:"d6cee834",5138:"28ba2067",5170:"4853c20d",5180:"e6f66bfb",5198:"7046ae9e",5235:"5db9e4f0",5281:"60280a86",5282:"1619fe9d",5316:"3e4aebed",5356:"5b04a0fd",5362:"c8a6a4d4",5409:"7604d7f6",5473:"66c89998",5511:"72adee05",5515:"24227d4e",5518:"0ae573d4",5526:"577742e6",5547:"d3e945b5",5558:"caf36d3c",5619:"e0a8dc5d",5646:"a8952612",5675:"6fcf2c6d",5730:"89351c93",5738:"d433d098",5747:"3d779569",5761:"8417400f",5762:"4af7f962",5766:"e10357e1",5779:"7ed996b5",5830:"e280e7eb",5832:"7ddfdfab",5856:"5581a186",5884:"db46fb20",5923:"69a4785b",5962:"bb48107c",5981:"a92797bd",6009:"a4ac47c1",6053:"2aca0642",6086:"09b72467",6088:"853bf41f",6095:"936ca227",6123:"de206452",6145:"7d53c238",6151:"fd1e7675",6158:"7331e278",6192:"c65ae7cf",6205:"bc014f19",6209:"c6c9389a",6219:"7c3e335b",6253:"73089ca7",6266:"ac099204",6337:"a3f13e2b",6361:"e7db4435",6364:"a2e3b42d",6369:"fee6f6db",6408:"702ad825",6427:"7f5efebe",6473:"7808e72a",6481:"18ddacc7",6487:"697480e4",6523:"ffdbfcf5",6537:"28608207",6556:"18c79ff2",6579:"25f18bdb",6599:"3dc46451",6621:"fe654e35",6628:"d4092ec3",6681:"f9d0f062",6700:"4e1435c5",6714:"56296377",6729:"ba618513",6730:"e5c9ae06",6766:"d58f5d8d",6874:"a60d43a7",6894:"e48c7385",6912:"80c470cf",6918:"a43926d8",6924:"757b91f1",6925:"4dc114b5",6931:"97fc0087",6961:"1bebe130",6972:"7e63c51e",6981:"e7a221c7",6984:"a7d5d237",6986:"cd744d8f",7035:"f74b51d2",7041:"4dc9730b",7042:"a1c01304",7045:"546b0d97",7107:"75bea3c5",7110:"4554c7eb",7116:"4897f28c",7141:"b14499df",7143:"72e37720",7146:"13c08a29",7200:"8a60f2ff",7248:"d9018415",7258:"12ef6432",7321:"df295bf1",7326:"7f16b068",7341:"56c56ba2",7362:"77a3fb64",7371:"78d6c143",7373:"e9c309d4",7382:"ca58e052",7471:"ae7e2a2c",7483:"f7fab1ba",7492:"88a58c68",7542:"33587268",7544:"c3f50066",7575:"e13c7382",7591:"687e3b9b",7696:"1c791804",7735:"dcbaa6f6",7757:"5662be3c",7800:"49a33252",7846:"5b80a366",7858:"ffe79b51",7868:"ff2fe3de",7906:"8519d884",7924:"0f1cba51",7938:"71ef8366",7940:"2f596615",7942:"e630317e",8023:"3862c567",8025:"c7a36617",8028:"45448590",8042:"c9e9fd52",8055:"d0fb13f2",8059:"ca5ec74e",8060:"19fef1a9",8087:"8c4f08ae",8093:"08f8a0a8",8100:"b8ecca35",8107:"ca35de63",8112:"58b0ec3b",8158:"5d3c0904",8166:"a2aad2f1",8173:"47aa1931",8177:"27151cdf",8194:"ad4896b0",8260:"45e84105",8267:"7392e77a",8309:"cf629d6f",8313:"b4685fa8",8327:"bd39cc06",8330:"41f33cbc",8350:"080987fe",8357:"76f4300b",8372:"26873cdb",8401:"66024bca",8414:"9174cb01",8457:"a4a94e63",8470:"d93ecfdd",8478:"7b197969",8483:"459d0ef1",8526:"6f9d53c5",8542:"7eec6184",8548:"6c319671",8581:"5cadb39b",8588:"0ee436f4",8607:"ee46c7a9",8621:"9d21528d",8628:"1970d743",8633:"142b8e9f",8688:"e54ebabe",8703:"29ddbf91",8714:"89f94980",8718:"f04a2c05",8722:"75fbabf5",8735:"50d9064f",8798:"0dd10615",8868:"630b68d3",8871:"af064a87",8873:"4eba4643",8913:"1f670d9b",8919:"64c72590",8933:"1b4b2049",8945:"67c1d44f",8950:"6293e55c",8997:"af38cde8",9008:"7b8c1194",9013:"722fb0cd",9026:"15bff0c5",9032:"7d2208c1",9040:"1d93a1b0",9062:"000a052a",9092:"63771824",9096:"38721118",9097:"7ec5ba9d",9127:"b932bba2",9158:"d1d61a3f",9219:"60fff3a5",9227:"1528c28d",9249:"4fe1c35b",9255:"f01d1130",9262:"bfbca50a",9271:"15789c24",9282:"5cb693a0",9336:"d4fc2faa",9368:"b230beae",9439:"5a4dc1f3",9441:"6caf9e22",9445:"2245fbeb",9454:"6ff8df15",9472:"2c7ce80d",9581:"f6dce50e",9594:"4951bde3",9606:"65bfc82c",9624:"a02a214d",9661:"91835414",9717:"88a5e9dd",9742:"ab33b329",9775:"dcfd472d",9778:"5353010a",9793:"1daf1c02",9798:"1331fed5",9810:"b533069a",9828:"b2e76004",9866:"c61535a0",9870:"32145f60",9917:"f499f373",9949:"8e8cc309"}[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,c)=>Object.prototype.hasOwnProperty.call(e,c),d={},r.l=(e,c,a,b)=>{if(d[e])d[e].push(c);else{var f,t;if(void 0!==a)for(var o=document.getElementsByTagName("script"),n=0;n{f.onerror=f.onload=null,clearTimeout(l);var b=d[e];if(delete d[e],f.parentNode&&f.parentNode.removeChild(f),b&&b.forEach((e=>e(a))),c)return c(a)},l=setTimeout(u.bind(null,void 0,{type:"timeout",target:f}),12e4);f.onerror=u.bind(null,f.onerror),f.onload=u.bind(null,f.onload),t&&document.head.appendChild(f)}},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:"8873",17896441:"8401",18100524:"1264",23794275:"1776",38317547:"4225",61595218:"9775",78619623:"6209",85339969:"7141",95073452:"5962",95576100:"1898",96877411:"5526",e196b408:"2","1e138b9d":"40",a27ea030:"68","1e7fe27e":"79","58d52345":"81","5e352ef4":"104","8f967659":"109",c7e7ae18:"152","652c74f1":"211","4bdafdff":"222","767c28af":"229",beccb025:"247","5dde70bf":"288",f2710c27:"321",f309eabc:"324","085c135f":"362","68b7d615":"436","2bbfc5d5":"458",a3a193a6:"464",b5d32d98:"481",a30fd8ca:"501","08fe23a4":"514",c007fb39:"521","7f74c501":"540",b35d1284:"552","89ed63c8":"573",a9bc4f03:"629",ac8293fa:"630",bb5ef1b7:"651",b6722b03:"663",f7c03581:"770",e126d786:"776",a13f3cdc:"835","606959d6":"862","0e5befdb":"932","48fde361":"958","528fe65e":"1027",eca0cf35:"1039",a27f6be0:"1062",b2d9540a:"1084","4dfeb783":"1126",eaa287f0:"1133",c4d37b36:"1141","6c14a231":"1188","6d89025c":"1190",c10d4a63:"1235","1edb88e5":"1245","02c5a8b1":"1289",c7a4caa1:"1308","4f59166d":"1340","2e25c87f":"1345","1ca907c0":"1431","4d68b066":"1443",d9523c62:"1465",b26a5b84:"1481","8f7fa040":"1505",fa41c0e9:"1538","9bd507da":"1565","843ebfb4":"1585","3c86ad25":"1587","4dd5816e":"1604","21cde469":"1653",d8ff000f:"1661","2f36012a":"1674","2fc68ddc":"1763",e39283a8:"1766",b4657038:"1886",aa5b6080:"1894","55c77f1e":"1930","23a8ac29":"1950",c3701568:"1968","7ade2db5":"1975","27258a7d":"1985","9000b231":"2032",common:"2076",b69ed219:"2089","1ea13486":"2112",cd25a595:"2113",e7ffb4b4:"2119","1a4e3797":"2138","4d049718":"2156","07666c14":"2174",dc9a99e0:"2187","94ecc552":"2197","1aa05129":"2207","0db959c8":"2227","8b6bafea":"2230","3d2d0a86":"2235",c275698c:"2248","5ececfab":"2275",a9125b44:"2301",bfe5398f:"2311","5e21a9be":"2347",aa675676:"2358","079b0d3e":"2369","7ee46e43":"2400",f4e1d1ba:"2421","25d4129e":"2459","1e2c5f46":"2491","4f4b6633":"2589","8f7abfe1":"2592","1d20a4b3":"2596",e7672013:"2600",c5fa393d:"2605",c4f5d8e4:"2634",ca36df4d:"2674","5ec7a7fe":"2676","4c5bf49d":"2720","01fe3043":"2743","69f2ab1f":"2784",b9ea999a:"2830","29cf2ad6":"2858","7e507331":"2862","36ddade1":"2917","0df2ba32":"2935",bcc01c83:"2952",db6a6f31:"2958","64536e1a":"2960","1f5af0f2":"2962","23f642f2":"2964","1af245cd":"2965",ae0a12ed:"2998","242d99d9":"3088","4aab8b8c":"3126","4f6c3156":"3137",cc1f18af:"3177","7d4976a8":"3195",bcb6471f:"3196","9953ecde":"3308","71a56230":"3332",b5d0ac54:"3343","5fa4a5b6":"3355",e91daeb9:"3359","21a7a3b0":"3382","756c6ac7":"3419",e617c97b:"3449","5e457383":"3457","1891fd2b":"3460","68e30702":"3468","77cdcd82":"3507","3a3e6a89":"3565","82395e72":"3576","3f944aba":"3585","579cc8d4":"3610","22e1e32f":"3613","263ebc7a":"3642",b103c05a:"3672","5a9b411c":"3693","8d81badd":"3701",d49884c9:"3712","1428bdad":"3723","0343976d":"3765",b7442939:"3781","4445fe20":"3811","24aca886":"3820",aba5bf07:"3955","16565e6a":"3962",ce95b17c:"4000","9073923c":"4017","03abab96":"4021","56279b5e":"4032","78da31a1":"4053","20540af3":"4054","6b4e0fb4":"4086",d07ad772:"4103",cddcd4e6:"4116","5ffc8074":"4122",e8a97ac3:"4124",a16ee953:"4224","87089bce":"4253","610e7425":"4279","5b80a12a":"4299",e806c7bf:"4324","65b8d1d1":"4330","16017aa6":"4366","56af72f6":"4368","27e787ca":"4393","18d6c9c9":"4422","7afb60b1":"4438",a7159008:"4474","59b1a96c":"4485",d3540d59:"4513",d8037f4c:"4548","7b54f5d5":"4565",a228ae9b:"4619","05fed6b1":"4620",e4c5fdc3:"4664","1d703573":"4671",f48e2589:"4690","2f46a9d9":"4706",ba7653ad:"4716","1e6ec01e":"4761","232afa3a":"4762","5945e8b0":"4773",a320b509:"4779","332827b4":"4780","06c02cc7":"4803","6efd6ec9":"4805",d4446569:"4807","03c886f6":"4827",e688cd7e:"4840","4e1a0951":"4843",a0bf4a5f:"4876","74383bd8":"4884","9f0ecd2e":"4893",aa52484c:"4919","26a27afb":"4954",b6a6a31f:"4955",e5d0e3cb:"4978","4e73bd72":"4981","2d02c83c":"5000",c953ec08:"5011",bdb33130:"5049","73ccb1b9":"5083","05e8cfc0":"5091","1b1927f4":"5099",b4aea2ce:"5138","6c8ff36a":"5170","366cfce3":"5180","143f7888":"5198","6fe30f11":"5235",cd699560:"5281",eec7caa6:"5282",c8bdc4df:"5316","60d99771":"5356","323a980a":"5362","38cf1c7a":"5409","3b58261a":"5473",fa1dd05c:"5511",cc08685c:"5515",e347e63a:"5518","565a5567":"5547","3d0eb74d":"5558","7bf967bc":"5619","612b773e":"5646","5285d58e":"5675","32e2b5e3":"5730",eb333c39:"5738",b370b50c:"5747","0fad1f8b":"5761","6c124661":"5762","8e97f284":"5766","85c72337":"5779",f90c5a21:"5830",bb9fe7c3:"5832","90e0b7fd":"5856",e29eb381:"5884","27b414e3":"5923","0d7bb119":"5981","8299d165":"6009","17cca601":"6053","136c1ee9":"6086","13b4aeb1":"6088","741df2ae":"6095",a2d3d8d2:"6123","2355609d":"6145",c933a311:"6151","0fd21208":"6158",c69dda99:"6192","4ed8ec4c":"6205",a91c1a62:"6219","999289d8":"6253",be1f0304:"6266",a28aff23:"6337",d74b5642:"6361",d4a334ea:"6364","96fc29fc":"6369","107b7a36":"6408",b42f5805:"6427","107d11ee":"6473","2014e4e3":"6481","8223875c":"6487","8bf32d27":"6523","4a2da18c":"6537",d6b4b60c:"6556",d7067606:"6579","029c6d75":"6599","61c7d915":"6621",b94a1068:"6628","9bbf4a9a":"6681","394f3211":"6700","2b6906c9":"6714","15a79915":"6729","6ad31330":"6730","54ca8693":"6766",bda39da3:"6874","504e6c2d":"6894",c1fe0282:"6912","32562f03":"6918","617523b3":"6924","07623f9a":"6925","28c12eaf":"6931","400ddbbb":"6961","31b4e903":"6972",ece9cf29:"6981","7e63a40e":"6984","077a13b8":"6986","72d0dc3a":"7035","607daa94":"7041","12d3ef9e":"7042","72be5fd7":"7045","04610919":"7107","9749ab4a":"7110","4194805f":"7116",e6858589:"7143","5d95c2e4":"7146","1520c72c":"7200",e38ecde0:"7248",f9511b3d:"7258","26662da3":"7321","673df5d6":"7326",f07f4757:"7341","766e1cc8":"7362",c6df2ddc:"7371",f5b0a435:"7373","822cd419":"7382","0a57d896":"7471","30940d42":"7483",cc1c02fe:"7492",a264d631:"7542","9664ee55":"7544","8913b51a":"7575","1f5e9707":"7591","9206a32f":"7696","54c144e4":"7735","380575ae":"7757","623b6c78":"7800","947f2c39":"7846","89cae3a7":"7858","8e2662b8":"7868",b06c439f:"7906",d589d3a7:"7924","51b7da58":"7938",b0ed7ea5:"7940","354a9b78":"7942","15b5a907":"8023",dbf2bcb3:"8025","0db009bb":"8028","29a6c1ba":"8042",e1b8bb84:"8055",fe153c07:"8059",dab32d56:"8060","6a8c9872":"8087",a23a5b68:"8093","3b486936":"8100",e45c611c:"8107","0cb7e976":"8112","471c3e37":"8166",e68b092b:"8173",cf877cff:"8177","950394a4":"8194",e63ebe23:"8260","50122f86":"8267",a95c9e82:"8309","379bfe51":"8313",f9af357c:"8327",d62b7e4c:"8330","6c4340be":"8350",aebf35b6:"8357","57f5c28c":"8372",c0fa6485:"8414","509d2004":"8457","1ba75d10":"8470","2d4548df":"8478",acbaac14:"8483",b8487569:"8526",b9d6d6e5:"8542","346bcb92":"8548","935f2afb":"8581",a3c6f073:"8588",c1068675:"8607","4a07aaf0":"8621","5881f7ec":"8628","07c49ebd":"8633","4d00e03a":"8688",cb01db44:"8703","1be78505":"8714","75cc8326":"8718","64947e00":"8722","2917b31e":"8735","6cfcfcfb":"8798",f9063551:"8868","5fb37434":"8871",bf2a5963:"8919",f94b062c:"8933",e2e51976:"8945",ed0c0463:"8950","4a060504":"8997","24ac61c7":"9008","9d9f8394":"9013",bd2c4a98:"9026","21637dff":"9032",e5d7b215:"9040",caa79efa:"9062","2ef99682":"9092","7b417fb4":"9096","102de343":"9097","2b26025e":"9127","8c95fc16":"9158","36b1b0cc":"9219","7c27e34c":"9227",c329487f:"9249","0ef60658":"9255","9279cea7":"9262","7810a993":"9271",d4c8693b:"9282","5d7590c2":"9336","2830ce57":"9368","8f951ce3":"9439",a55b0daf:"9441","6c6ce37c":"9445","5bc7272e":"9454","4c7f7507":"9472","4f30448a":"9581",c32ff706:"9594","5792f9ba":"9606","2e301473":"9624",cd30f404:"9661","976f6afc":"9717","820db038":"9742","9d336ee4":"9778","0370fbfb":"9793","58e6b30f":"9798","859fcda7":"9810",d6188fd4:"9828",a99e9943:"9866","7515d7ec":"9870","91e22cb6":"9917",a1e3d512:"9949"}[e]||e,r.p+r.u(e)},(()=>{var e={5354:0,1869:0};r.f.j=(c,a)=>{var d=r.o(e,c)?e[c]:void 0;if(0!==d)if(d)a.push(d[2]);else if(/^(1869|5354)$/.test(c))e[c]=0;else{var b=new Promise(((a,b)=>d=e[c]=[a,b]));a.push(d[2]=b);var f=r.p+r.u(c),t=new Error;r.l(f,(a=>{if(r.o(e,c)&&(0!==(d=e[c])&&(e[c]=void 0),d)){var b=a&&("load"===a.type?"missing":a.type),f=a&&a.target&&a.target.src;t.message="Loading chunk "+c+" failed.\n("+b+": "+f+")",t.name="ChunkLoadError",t.type=b,t.request=f,d[1](t)}}),"chunk-"+c,c)}},r.O.j=c=>0===e[c];var c=(c,a)=>{var d,b,f=a[0],t=a[1],o=a[2],n=0;if(f.some((c=>0!==e[c]))){for(d in t)r.o(t,d)&&(r.m[d]=t[d]);if(o)var i=o(r)}for(c&&c(a);n