From 86e7d98fab03a295a612f2b19995e388fc31c857 Mon Sep 17 00:00:00 2001 From: oojacoboo Date: Mon, 7 Oct 2024 21:21:00 +0000 Subject: [PATCH] =?UTF-8?q?Deploying=20to=20gh-pages=20from=20@=20thecodin?= =?UTF-8?q?gmachine/graphqlite@68de6c957349591e93307e02205799b0c4d74c64=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.9fc68b60.js => 01fe3043.b722dfb6.js} | 2 +- assets/js/{029c6d75.34cc9a73.js => 029c6d75.903e79a5.js} | 2 +- assets/js/{02c5a8b1.77711b74.js => 02c5a8b1.68048805.js} | 2 +- assets/js/{0343976d.3e3be5ef.js => 0343976d.0dc24357.js} | 2 +- assets/js/{0370fbfb.81068cea.js => 0370fbfb.a59bfdcd.js} | 2 +- assets/js/{03abab96.1f8b34ea.js => 03abab96.0060c15e.js} | 2 +- assets/js/{03c886f6.45a05f02.js => 03c886f6.4fbdf0ac.js} | 2 +- assets/js/{05e8cfc0.50d9e5fd.js => 05e8cfc0.8fa218cc.js} | 2 +- assets/js/{05fed6b1.5db9e3a1.js => 05fed6b1.f422f54a.js} | 2 +- assets/js/{06c02cc7.6f61e4dd.js => 06c02cc7.eee16367.js} | 2 +- assets/js/{07623f9a.21183fdc.js => 07623f9a.cdea6839.js} | 2 +- assets/js/{07666c14.9aceff08.js => 07666c14.aec3a10d.js} | 2 +- assets/js/{077a13b8.76a36fb7.js => 077a13b8.9e4db38f.js} | 2 +- assets/js/{079b0d3e.d9e3d7f8.js => 079b0d3e.3179f033.js} | 2 +- assets/js/{07c49ebd.3ead5716.js => 07c49ebd.04705fa2.js} | 2 +- assets/js/{085c135f.52279798.js => 085c135f.c4f91d04.js} | 2 +- assets/js/{08fe23a4.2dec6eeb.js => 08fe23a4.e92b4838.js} | 2 +- assets/js/{0a57d896.22dde59a.js => 0a57d896.9763be6f.js} | 2 +- assets/js/{0cb7e976.3c43838b.js => 0cb7e976.f6ed1648.js} | 2 +- assets/js/{0d7bb119.9167846c.js => 0d7bb119.d4075bc3.js} | 2 +- assets/js/{0db009bb.5a41a9e3.js => 0db009bb.88754719.js} | 2 +- assets/js/{0db959c8.cd0b2ed7.js => 0db959c8.19be7258.js} | 2 +- assets/js/{0df2ba32.c73ffdf3.js => 0df2ba32.4d5523d8.js} | 2 +- assets/js/{0e5befdb.9bb42ee8.js => 0e5befdb.adfcf147.js} | 2 +- assets/js/{0ef60658.3a8223fb.js => 0ef60658.3a0dda98.js} | 2 +- assets/js/{0fd21208.cef60eb6.js => 0fd21208.c7e0a6a1.js} | 2 +- assets/js/{102de343.cac6183f.js => 102de343.ac9aff92.js} | 2 +- assets/js/{107b7a36.67eb69dc.js => 107b7a36.ef8bab33.js} | 2 +- assets/js/{107d11ee.617e845b.js => 107d11ee.6b209a8d.js} | 2 +- assets/js/{12d3ef9e.2316a90f.js => 12d3ef9e.e1898768.js} | 2 +- assets/js/{136c1ee9.ee344fe1.js => 136c1ee9.1431f6c1.js} | 2 +- assets/js/{13b4aeb1.f687627c.js => 13b4aeb1.40ffa096.js} | 2 +- assets/js/{1428bdad.6eaa2756.js => 1428bdad.2f645659.js} | 2 +- assets/js/{143f7888.f3942f77.js => 143f7888.1d5adaec.js} | 2 +- assets/js/{15a79915.33beb644.js => 15a79915.be719ff6.js} | 2 +- assets/js/{15b5a907.2688abf0.js => 15b5a907.3d50e40d.js} | 2 +- assets/js/{16017aa6.3eccad0d.js => 16017aa6.a22be57e.js} | 2 +- assets/js/{16565e6a.94dbe306.js => 16565e6a.085e15ac.js} | 2 +- assets/js/{17518879.37f744be.js => 17518879.ea89b826.js} | 2 +- assets/js/{17cca601.007c3177.js => 17cca601.e8423ab3.js} | 2 +- assets/js/{18100524.fb2d6eb2.js => 18100524.2a11f212.js} | 2 +- assets/js/{1891fd2b.bc507d40.js => 1891fd2b.175c467d.js} | 2 +- assets/js/{18d6c9c9.9b1b6d63.js => 18d6c9c9.b0c01362.js} | 2 +- assets/js/{1aa05129.a3079b3b.js => 1aa05129.c0cd2084.js} | 2 +- assets/js/{1af245cd.c56b680a.js => 1af245cd.d7e67aae.js} | 2 +- assets/js/{1b1927f4.569471ed.js => 1b1927f4.a9a56397.js} | 2 +- assets/js/{1ba75d10.15824987.js => 1ba75d10.d2fc3080.js} | 2 +- assets/js/{1ca907c0.b2e2ea24.js => 1ca907c0.880728de.js} | 2 +- assets/js/{1d20a4b3.86bf69c5.js => 1d20a4b3.7b84c748.js} | 2 +- assets/js/{1d703573.c3571e4c.js => 1d703573.6488b685.js} | 2 +- assets/js/{1e2c5f46.b48d6e58.js => 1e2c5f46.def37f02.js} | 2 +- assets/js/{1e6ec01e.a9f97779.js => 1e6ec01e.79a26d94.js} | 2 +- assets/js/{1e7fe27e.10e1b4b0.js => 1e7fe27e.d543f284.js} | 2 +- assets/js/{1ea13486.8e8b73ef.js => 1ea13486.621658df.js} | 2 +- assets/js/{1edb88e5.9b4e4601.js => 1edb88e5.c186a972.js} | 2 +- assets/js/{1f5af0f2.b23e918f.js => 1f5af0f2.1e16655c.js} | 2 +- assets/js/{1f5e9707.bd784f60.js => 1f5e9707.cb48452a.js} | 2 +- assets/js/{2014e4e3.9a25270f.js => 2014e4e3.f5c34a4b.js} | 2 +- assets/js/{20540af3.bc6f4eb1.js => 20540af3.7b8b47f6.js} | 2 +- assets/js/{21637dff.cfa95698.js => 21637dff.bc0d8785.js} | 2 +- assets/js/{21a7a3b0.e2584029.js => 21a7a3b0.98695aa2.js} | 2 +- assets/js/{21cde469.2dda92b3.js => 21cde469.42de3ab5.js} | 2 +- assets/js/{22e1e32f.46a87359.js => 22e1e32f.a63c9c7d.js} | 2 +- assets/js/{232afa3a.6102f5c2.js => 232afa3a.4989b07d.js} | 2 +- assets/js/{2355609d.ec196a8f.js => 2355609d.3ad1d9e5.js} | 2 +- assets/js/{23794275.be36c6f0.js => 23794275.2d3cafaf.js} | 2 +- assets/js/{23a8ac29.6f8e7fa6.js => 23a8ac29.fef39a38.js} | 2 +- assets/js/{23f642f2.eb057b4d.js => 23f642f2.702af88f.js} | 2 +- assets/js/{242d99d9.ff085183.js => 242d99d9.65e7903b.js} | 2 +- assets/js/{24ac61c7.0594428c.js => 24ac61c7.56754f4a.js} | 2 +- assets/js/{24aca886.7f44594c.js => 24aca886.067e7bc9.js} | 2 +- assets/js/{25d4129e.57911023.js => 25d4129e.0452c424.js} | 2 +- assets/js/{263ebc7a.fd45594c.js => 263ebc7a.ab66a253.js} | 2 +- assets/js/{26662da3.c3e74a31.js => 26662da3.fe57afd5.js} | 2 +- assets/js/{26a27afb.ecb27e90.js => 26a27afb.f2ee3b29.js} | 2 +- assets/js/{27258a7d.11b80646.js => 27258a7d.c02372c5.js} | 2 +- assets/js/{27b414e3.20ddf17d.js => 27b414e3.a918f7e4.js} | 2 +- assets/js/{28c12eaf.f79d3873.js => 28c12eaf.0bf95a09.js} | 2 +- assets/js/{2917b31e.4ec91853.js => 2917b31e.f9c0b568.js} | 2 +- assets/js/{29a6c1ba.be7c1a69.js => 29a6c1ba.771a3fc1.js} | 2 +- assets/js/{29cf2ad6.e5209db4.js => 29cf2ad6.f26d1860.js} | 2 +- assets/js/{2b26025e.a2d49345.js => 2b26025e.2350cefd.js} | 2 +- assets/js/{2bbfc5d5.b4e123c4.js => 2bbfc5d5.545fc5e5.js} | 2 +- assets/js/{2d02c83c.df37da76.js => 2d02c83c.42480db1.js} | 2 +- assets/js/{2d4548df.87e9f636.js => 2d4548df.5485b326.js} | 2 +- assets/js/{2e25c87f.ea5ae136.js => 2e25c87f.05446db0.js} | 2 +- assets/js/{2e301473.3cc314c9.js => 2e301473.e6e2c4aa.js} | 2 +- assets/js/{2ef99682.a4397b07.js => 2ef99682.5ea187f2.js} | 2 +- assets/js/{2f36012a.6f491d09.js => 2f36012a.16b48290.js} | 2 +- assets/js/{30940d42.4f0f3c44.js => 30940d42.e7f62cec.js} | 2 +- assets/js/{31b4e903.04610a44.js => 31b4e903.6bbd747e.js} | 2 +- assets/js/{323a980a.6b82ac7e.js => 323a980a.13853cf0.js} | 2 +- assets/js/{332827b4.d4c1e857.js => 332827b4.f5ff9c8a.js} | 2 +- assets/js/{346bcb92.89b2ce95.js => 346bcb92.16595548.js} | 2 +- assets/js/{354a9b78.cedd99eb.js => 354a9b78.46c818e8.js} | 2 +- assets/js/{366cfce3.4f5e8a84.js => 366cfce3.072044f3.js} | 2 +- assets/js/{36ddade1.e248315d.js => 36ddade1.52451906.js} | 2 +- assets/js/{379bfe51.7edce05a.js => 379bfe51.ae5ebb8e.js} | 2 +- assets/js/{380575ae.cb57eedc.js => 380575ae.0fb3b47d.js} | 2 +- assets/js/{38317547.f454350d.js => 38317547.a1b9180d.js} | 2 +- assets/js/{38cf1c7a.c56a066d.js => 38cf1c7a.01e4fa32.js} | 2 +- assets/js/{394f3211.60a413eb.js => 394f3211.81f00e53.js} | 2 +- assets/js/{3b486936.410100a2.js => 3b486936.e4e39654.js} | 2 +- assets/js/{3d0eb74d.c0a1bbde.js => 3d0eb74d.2b99da9d.js} | 2 +- assets/js/{3d2d0a86.82169c25.js => 3d2d0a86.49c0e414.js} | 2 +- assets/js/{3f944aba.83281771.js => 3f944aba.3c25cf0e.js} | 2 +- assets/js/{400ddbbb.82e55cef.js => 400ddbbb.9a45cf17.js} | 2 +- assets/js/{4194805f.6b3b89b3.js => 4194805f.a49fe3a4.js} | 2 +- assets/js/{471c3e37.2a377d4d.js => 471c3e37.93d9c059.js} | 2 +- assets/js/{48fde361.1f0fc197.js => 48fde361.98272508.js} | 2 +- assets/js/{4a060504.83af7d17.js => 4a060504.2f73632b.js} | 2 +- assets/js/{4a07aaf0.ac98ae89.js => 4a07aaf0.9163f54f.js} | 2 +- assets/js/{4a2da18c.4eb1119f.js => 4a2da18c.2de5b1b3.js} | 2 +- assets/js/{4aab8b8c.89b3df88.js => 4aab8b8c.7218bae3.js} | 2 +- assets/js/{4bdafdff.73a284a0.js => 4bdafdff.0a931b29.js} | 2 +- assets/js/{4c5bf49d.4ac6e79a.js => 4c5bf49d.a481b861.js} | 2 +- assets/js/{4c7f7507.c8dd7aab.js => 4c7f7507.02676f01.js} | 2 +- assets/js/{4d00e03a.9dff7708.js => 4d00e03a.91ddc8d5.js} | 2 +- assets/js/{4d049718.bd40789e.js => 4d049718.73044c16.js} | 2 +- assets/js/{4d68b066.ea6539f6.js => 4d68b066.83f4dcfb.js} | 2 +- assets/js/{4dd5816e.1347aa25.js => 4dd5816e.ea996778.js} | 2 +- assets/js/{4dfeb783.faf621ba.js => 4dfeb783.f77b3a45.js} | 2 +- assets/js/{4e1a0951.3f9b7190.js => 4e1a0951.d5de8cab.js} | 2 +- assets/js/{4e73bd72.3b18a39d.js => 4e73bd72.8da00f07.js} | 2 +- assets/js/{4f30448a.cc668b1d.js => 4f30448a.e44fb11b.js} | 2 +- assets/js/{4f4b6633.f4ad5c07.js => 4f4b6633.4ebd402a.js} | 2 +- assets/js/{4f59166d.a1b41e48.js => 4f59166d.41f72369.js} | 2 +- assets/js/{4f6c3156.634f36b4.js => 4f6c3156.4814e7e0.js} | 2 +- assets/js/{50122f86.e7054e4a.js => 50122f86.0f469e64.js} | 2 +- assets/js/{504e6c2d.cfc4398d.js => 504e6c2d.47ec9159.js} | 2 +- assets/js/{509d2004.714400f3.js => 509d2004.1a6cb1b3.js} | 2 +- assets/js/{5285d58e.92cac4ae.js => 5285d58e.a659173f.js} | 2 +- assets/js/{528fe65e.c60be34d.js => 528fe65e.722571e6.js} | 2 +- assets/js/{54c144e4.9c598b07.js => 54c144e4.bb6063dc.js} | 2 +- assets/js/{54ca8693.de282c9d.js => 54ca8693.d08449f0.js} | 2 +- assets/js/{55c77f1e.00046a46.js => 55c77f1e.6554dceb.js} | 2 +- assets/js/{56279b5e.9367e8fe.js => 56279b5e.668f312e.js} | 2 +- assets/js/{565a5567.249b1f26.js => 565a5567.933d5222.js} | 2 +- assets/js/{56af72f6.5b19550c.js => 56af72f6.e60a700d.js} | 2 +- assets/js/{5792f9ba.1f23575a.js => 5792f9ba.00b9b662.js} | 2 +- assets/js/{579cc8d4.ed347d2a.js => 579cc8d4.1da1a812.js} | 2 +- assets/js/{57f5c28c.6e73b6ce.js => 57f5c28c.6aacba73.js} | 2 +- assets/js/{5881f7ec.00fefab5.js => 5881f7ec.9163213f.js} | 2 +- assets/js/{58d52345.57520c92.js => 58d52345.26ba55c3.js} | 2 +- assets/js/{58e6b30f.6820b216.js => 58e6b30f.2faed412.js} | 2 +- assets/js/{5945e8b0.e70e6fa1.js => 5945e8b0.efe55108.js} | 2 +- assets/js/{59b1a96c.c8c5d980.js => 59b1a96c.4b55b1e2.js} | 2 +- assets/js/{5a9b411c.ce6f95a4.js => 5a9b411c.559a6713.js} | 2 +- assets/js/{5bc7272e.0771ddb5.js => 5bc7272e.980951c9.js} | 2 +- assets/js/{5d7590c2.d21d7c9f.js => 5d7590c2.bc73a967.js} | 2 +- assets/js/{5dde70bf.fcf84c6a.js => 5dde70bf.b5740b86.js} | 2 +- assets/js/{5e21a9be.e8721d31.js => 5e21a9be.b6d9b713.js} | 2 +- assets/js/{5e352ef4.7431f3bd.js => 5e352ef4.cec79076.js} | 2 +- assets/js/{5e457383.cd22f35c.js => 5e457383.24cd44b0.js} | 2 +- assets/js/{5ec7a7fe.75d547c0.js => 5ec7a7fe.9f7d2515.js} | 2 +- assets/js/{5ececfab.321e03dd.js => 5ececfab.81c29f92.js} | 2 +- assets/js/{5fa4a5b6.4a59bbf6.js => 5fa4a5b6.0c5693e2.js} | 2 +- assets/js/{5ffc8074.41ae9a58.js => 5ffc8074.382b4640.js} | 2 +- assets/js/{606959d6.12b37f8d.js => 606959d6.2d95a4c6.js} | 2 +- assets/js/{60d99771.6eee9b87.js => 60d99771.ac4342ef.js} | 2 +- assets/js/{610e7425.d2835569.js => 610e7425.22b083d8.js} | 2 +- assets/js/{612b773e.7d6b0229.js => 612b773e.e479b012.js} | 2 +- assets/js/{61595218.74330fc8.js => 61595218.ebfdff1a.js} | 2 +- assets/js/{617523b3.88a4d717.js => 617523b3.79ae2a0c.js} | 2 +- assets/js/{61c7d915.ddc67bf7.js => 61c7d915.0a2b168b.js} | 2 +- assets/js/{623b6c78.bc73ad97.js => 623b6c78.d7c4e3d8.js} | 2 +- assets/js/{64536e1a.07bf472c.js => 64536e1a.e0906f5a.js} | 2 +- assets/js/{64947e00.ed002f1f.js => 64947e00.ec66addf.js} | 2 +- assets/js/{652c74f1.3e38ddd7.js => 652c74f1.6359bb26.js} | 2 +- assets/js/{65b8d1d1.8d1b90a0.js => 65b8d1d1.d8e12cac.js} | 2 +- assets/js/{673df5d6.895ad17e.js => 673df5d6.a9b22576.js} | 2 +- assets/js/{68b7d615.07386ae0.js => 68b7d615.9c5c0e30.js} | 2 +- assets/js/{68e30702.fe37ea89.js => 68e30702.5028a35e.js} | 2 +- assets/js/{69f2ab1f.051152f6.js => 69f2ab1f.8ca20958.js} | 2 +- assets/js/{6a8c9872.3340519d.js => 6a8c9872.7ccea129.js} | 2 +- assets/js/{6ad31330.27875216.js => 6ad31330.e6d3127b.js} | 2 +- assets/js/{6c124661.7cbe5021.js => 6c124661.ef09a451.js} | 2 +- assets/js/{6c14a231.d3c7ec0b.js => 6c14a231.1d305f75.js} | 2 +- assets/js/{6c4340be.1aaa0aca.js => 6c4340be.df1dad05.js} | 2 +- assets/js/{6c6ce37c.00a01a79.js => 6c6ce37c.9f1a930b.js} | 2 +- assets/js/{6cfcfcfb.538269ec.js => 6cfcfcfb.d44b9f3a.js} | 2 +- assets/js/{6d89025c.0ed36bbc.js => 6d89025c.2bba48c9.js} | 2 +- assets/js/{6efd6ec9.054a55e6.js => 6efd6ec9.7ee75f12.js} | 2 +- assets/js/{6fe30f11.63909169.js => 6fe30f11.1772048a.js} | 2 +- assets/js/{71a56230.30d486bb.js => 71a56230.2f5cd36c.js} | 2 +- assets/js/{72be5fd7.72da73d5.js => 72be5fd7.5f11d860.js} | 2 +- assets/js/{72d0dc3a.8a2fadd5.js => 72d0dc3a.757595fe.js} | 2 +- assets/js/{741df2ae.d7ee228b.js => 741df2ae.8def9ec7.js} | 2 +- assets/js/{74383bd8.36d2c5e5.js => 74383bd8.52f7baf7.js} | 2 +- assets/js/{7515d7ec.3c6e0fa6.js => 7515d7ec.cd92088e.js} | 2 +- assets/js/{756c6ac7.182b31ca.js => 756c6ac7.c578852e.js} | 2 +- assets/js/{75cc8326.435bc032.js => 75cc8326.3c8456bf.js} | 2 +- assets/js/{766e1cc8.007f2971.js => 766e1cc8.5884e667.js} | 2 +- assets/js/{767c28af.ec7dc3fc.js => 767c28af.076047b9.js} | 2 +- assets/js/{77cdcd82.979607ae.js => 77cdcd82.121eed95.js} | 2 +- assets/js/{7810a993.263785f9.js => 7810a993.16409b83.js} | 2 +- assets/js/{78619623.5a6df041.js => 78619623.2a48f5b2.js} | 2 +- assets/js/{78da31a1.8e7ba28c.js => 78da31a1.81a56c02.js} | 2 +- assets/js/{7afb60b1.a34d9d6f.js => 7afb60b1.1b724298.js} | 2 +- assets/js/{7b54f5d5.b5df9ba2.js => 7b54f5d5.ad75730f.js} | 2 +- assets/js/{7bf967bc.02928b46.js => 7bf967bc.76cb6139.js} | 2 +- assets/js/{7c27e34c.c005f810.js => 7c27e34c.19b3c022.js} | 2 +- assets/js/{7e507331.672c2963.js => 7e507331.604dcbe9.js} | 2 +- assets/js/{7e63a40e.bc402124.js => 7e63a40e.e9c65e4c.js} | 2 +- assets/js/{7ee46e43.af9426ef.js => 7ee46e43.ac809c54.js} | 2 +- assets/js/{820db038.bdb67856.js => 820db038.336d5a20.js} | 2 +- assets/js/{822cd419.4bbdece7.js => 822cd419.eec8322d.js} | 2 +- assets/js/{82395e72.32f48466.js => 82395e72.d158cad6.js} | 2 +- assets/js/{8299d165.5a2348ca.js => 8299d165.45757bd5.js} | 2 +- assets/js/{843ebfb4.462347e3.js => 843ebfb4.8680fd03.js} | 2 +- assets/js/{85339969.0793324f.js => 85339969.cf5cbbcf.js} | 2 +- assets/js/{859fcda7.614c1383.js => 859fcda7.6f4e9cfc.js} | 2 +- assets/js/{85c72337.1def6368.js => 85c72337.68dbbe79.js} | 2 +- assets/js/{87089bce.e0da2805.js => 87089bce.c45cefa8.js} | 2 +- assets/js/{8913b51a.1b840764.js => 8913b51a.099434fd.js} | 2 +- assets/js/{89cae3a7.26a332e9.js => 89cae3a7.f2f58bf0.js} | 2 +- assets/js/{89ed63c8.cdb311ab.js => 89ed63c8.dab6893e.js} | 2 +- assets/js/{8b6bafea.c0ebbd9d.js => 8b6bafea.d38cc5d5.js} | 2 +- assets/js/{8bf32d27.5148b85d.js => 8bf32d27.2de9f795.js} | 2 +- assets/js/{8c95fc16.191afaf6.js => 8c95fc16.8c929c5b.js} | 2 +- assets/js/{8d81badd.81c8237f.js => 8d81badd.6701e780.js} | 2 +- assets/js/{8f7abfe1.7d38c4e5.js => 8f7abfe1.0827e6c1.js} | 2 +- assets/js/{8f7fa040.12aee849.js => 8f7fa040.19aa9fff.js} | 2 +- assets/js/{8f951ce3.686bd959.js => 8f951ce3.44fe12e6.js} | 2 +- assets/js/{8f967659.6820bbdd.js => 8f967659.2a8b80c0.js} | 2 +- assets/js/{9000b231.e4f1d685.js => 9000b231.2d7f009f.js} | 2 +- assets/js/{9073923c.2450bdcb.js => 9073923c.14428e5a.js} | 2 +- assets/js/{90e0b7fd.d1dbb559.js => 90e0b7fd.db56516a.js} | 2 +- assets/js/{9206a32f.5c74cb1b.js => 9206a32f.5c4bd34f.js} | 2 +- assets/js/{9279cea7.fe498c74.js => 9279cea7.308af6f9.js} | 2 +- assets/js/{947f2c39.ba2fa99a.js => 947f2c39.ab8670a7.js} | 2 +- assets/js/{950394a4.63eb0f08.js => 950394a4.ed70f17c.js} | 2 +- assets/js/{95576100.21e23958.js => 95576100.6ede392b.js} | 2 +- assets/js/{9664ee55.db3a0eb9.js => 9664ee55.dfc7699e.js} | 2 +- assets/js/{96877411.c0200494.js => 96877411.4913f2de.js} | 2 +- assets/js/{9749ab4a.7572e404.js => 9749ab4a.ddfa782f.js} | 2 +- assets/js/{976f6afc.a654a515.js => 976f6afc.503f4678.js} | 2 +- assets/js/{9953ecde.4888f0d5.js => 9953ecde.5bddb47b.js} | 2 +- assets/js/{9bd507da.4540c36c.js => 9bd507da.e9692c43.js} | 2 +- assets/js/{9d336ee4.15d9be2f.js => 9d336ee4.72a6efbc.js} | 2 +- assets/js/{9d9f8394.ec32e8ef.js => 9d9f8394.e9ef5f63.js} | 2 +- assets/js/{9f0ecd2e.1a01299d.js => 9f0ecd2e.f5db31e4.js} | 2 +- assets/js/{a0bf4a5f.e3ac7f51.js => a0bf4a5f.dcfbd033.js} | 2 +- assets/js/{a13f3cdc.600c339c.js => a13f3cdc.a5356667.js} | 2 +- assets/js/{a16ee953.b2b49229.js => a16ee953.0fbc4b46.js} | 2 +- assets/js/{a1e3d512.5f53de34.js => a1e3d512.07ea288b.js} | 2 +- assets/js/{a23a5b68.250a7b15.js => a23a5b68.35c6cfe4.js} | 2 +- assets/js/{a264d631.3aec4aef.js => a264d631.8c2e8f25.js} | 2 +- assets/js/{a27ea030.1e3d8131.js => a27ea030.421025a3.js} | 2 +- assets/js/{a27f6be0.f4c630d8.js => a27f6be0.93950472.js} | 2 +- assets/js/{a28aff23.1711f5a4.js => a28aff23.d95ba250.js} | 2 +- assets/js/{a2d3d8d2.8e3e1cb6.js => a2d3d8d2.6dcfb1a2.js} | 2 +- assets/js/{a30fd8ca.50645db0.js => a30fd8ca.615ed318.js} | 2 +- assets/js/{a320b509.ee5d6717.js => a320b509.7ab18136.js} | 2 +- assets/js/{a3a193a6.e6f82b19.js => a3a193a6.66147a15.js} | 2 +- assets/js/{a55b0daf.8b9c7c4f.js => a55b0daf.d5861c2c.js} | 2 +- assets/js/{a9125b44.ea36bda7.js => a9125b44.2e25c318.js} | 2 +- assets/js/{a91c1a62.2f51963a.js => a91c1a62.151c5c44.js} | 2 +- assets/js/{a95c9e82.74ac082a.js => a95c9e82.85a1f0cf.js} | 2 +- assets/js/{a99e9943.760f22fa.js => a99e9943.6c8a6d61.js} | 2 +- assets/js/{a9bc4f03.fa1f1757.js => a9bc4f03.b4a3dfa1.js} | 2 +- assets/js/{aa52484c.67b98c1e.js => aa52484c.74012053.js} | 2 +- assets/js/{aa5b6080.8403baf7.js => aa5b6080.5bf1d237.js} | 2 +- assets/js/{aa675676.60b0926d.js => aa675676.61394c21.js} | 2 +- assets/js/{aba5bf07.035001c1.js => aba5bf07.2edcb8ab.js} | 2 +- assets/js/{ac8293fa.efbab152.js => ac8293fa.5590a3a2.js} | 2 +- assets/js/{acbaac14.212ed806.js => acbaac14.df94e672.js} | 2 +- assets/js/{ae0a12ed.5aab8eff.js => ae0a12ed.3ea7f2e0.js} | 2 +- assets/js/{aebf35b6.9e1d2104.js => aebf35b6.2c35a4e2.js} | 2 +- assets/js/{b06c439f.1e48dcce.js => b06c439f.a328d225.js} | 2 +- assets/js/{b0ed7ea5.6e1fd2a9.js => b0ed7ea5.e78cbc24.js} | 2 +- assets/js/{b103c05a.abdaf47c.js => b103c05a.3f1db171.js} | 2 +- assets/js/{b26a5b84.df74297c.js => b26a5b84.70df5a5a.js} | 2 +- assets/js/{b2d9540a.8b170ae8.js => b2d9540a.94cb79db.js} | 2 +- assets/js/{b35d1284.f62c70b4.js => b35d1284.29c39c4b.js} | 2 +- assets/js/{b370b50c.ded65cc0.js => b370b50c.020852bb.js} | 2 +- assets/js/{b42f5805.3e26017e.js => b42f5805.c207b0b2.js} | 2 +- assets/js/{b4657038.0a64f0ff.js => b4657038.78fb71e5.js} | 2 +- assets/js/{b4aea2ce.b8c1c91c.js => b4aea2ce.e042c4be.js} | 2 +- assets/js/{b5d0ac54.06097821.js => b5d0ac54.0c090973.js} | 2 +- assets/js/{b5d32d98.fb4df112.js => b5d32d98.f3319d03.js} | 2 +- assets/js/{b6722b03.c33ad6bb.js => b6722b03.706f9763.js} | 2 +- assets/js/{b6a6a31f.f3cfb108.js => b6a6a31f.f3a4b1ab.js} | 2 +- assets/js/{b7442939.f1dfeb88.js => b7442939.6e0e3185.js} | 2 +- assets/js/{b8487569.8aa4dd2e.js => b8487569.34de94db.js} | 2 +- assets/js/{b94a1068.989eaf9b.js => b94a1068.70ece279.js} | 2 +- assets/js/{b9d6d6e5.a0a8a034.js => b9d6d6e5.ed929d1d.js} | 2 +- assets/js/{b9ea999a.54ec31ba.js => b9ea999a.a642f64a.js} | 2 +- assets/js/{ba7653ad.5b47d0d7.js => ba7653ad.bbc1d3a3.js} | 2 +- assets/js/{bb5ef1b7.e0206554.js => bb5ef1b7.2c1da688.js} | 2 +- assets/js/{bb9fe7c3.5f6f8397.js => bb9fe7c3.fe26e692.js} | 2 +- assets/js/{bcb6471f.d7d64164.js => bcb6471f.e5fedff8.js} | 2 +- assets/js/{bcc01c83.aeb7afc4.js => bcc01c83.a8d43fe5.js} | 2 +- assets/js/{bd2c4a98.00d5dde8.js => bd2c4a98.96e2d1cb.js} | 2 +- assets/js/{bda39da3.3356cab1.js => bda39da3.42af0747.js} | 2 +- assets/js/{bdb33130.d803a9da.js => bdb33130.60d5e579.js} | 2 +- assets/js/{be1f0304.730884bb.js => be1f0304.e6b63afc.js} | 2 +- assets/js/{beccb025.30f90fdb.js => beccb025.0cf1609c.js} | 2 +- assets/js/{bf2a5963.2a3df866.js => bf2a5963.8d2652ff.js} | 2 +- assets/js/{c007fb39.7a129435.js => c007fb39.78d67697.js} | 2 +- assets/js/{c0fa6485.d13d334d.js => c0fa6485.5373e105.js} | 2 +- assets/js/{c10d4a63.f2de6ddf.js => c10d4a63.b22f5985.js} | 2 +- assets/js/{c1fe0282.5c47ead6.js => c1fe0282.e663460d.js} | 2 +- assets/js/{c275698c.738c0c33.js => c275698c.fc512c41.js} | 2 +- assets/js/{c329487f.e61d729d.js => c329487f.d022b7c1.js} | 2 +- assets/js/{c3701568.24a3bd1a.js => c3701568.5cb9c150.js} | 2 +- assets/js/{c4d37b36.e63e72c1.js => c4d37b36.ebe7ba67.js} | 2 +- assets/js/{c5fa393d.317dd843.js => c5fa393d.c9ae6aa6.js} | 2 +- assets/js/{c69dda99.24f7f4ac.js => c69dda99.7bed8d0f.js} | 2 +- assets/js/{c7a4caa1.437fdf09.js => c7a4caa1.d204f912.js} | 2 +- assets/js/{c7e7ae18.62df2119.js => c7e7ae18.8214a40d.js} | 2 +- assets/js/{c8bdc4df.e0efc303.js => c8bdc4df.390ff8eb.js} | 2 +- assets/js/{c933a311.383732ef.js => c933a311.12e46a4a.js} | 2 +- assets/js/{c953ec08.04b40a4d.js => c953ec08.044ba5e1.js} | 2 +- assets/js/{ca36df4d.7e867049.js => ca36df4d.94c47d62.js} | 2 +- assets/js/{caa79efa.851f28bb.js => caa79efa.53b67792.js} | 2 +- assets/js/{cb01db44.364564ce.js => cb01db44.57683fd3.js} | 2 +- assets/js/{cc08685c.00b229fc.js => cc08685c.e931f2d8.js} | 2 +- assets/js/{cc1c02fe.14b8c14a.js => cc1c02fe.f50e1ffd.js} | 2 +- assets/js/{cc1f18af.509da543.js => cc1f18af.993e0004.js} | 2 +- assets/js/{cd25a595.6427617e.js => cd25a595.cedacea9.js} | 2 +- assets/js/{cd30f404.d4883c0f.js => cd30f404.ad234e4d.js} | 2 +- assets/js/{cd699560.560b6c61.js => cd699560.3152ae70.js} | 2 +- assets/js/{cddcd4e6.b97b3b81.js => cddcd4e6.b0f5a7d8.js} | 2 +- assets/js/{ce95b17c.0f107b8a.js => ce95b17c.d0a613b9.js} | 2 +- assets/js/{cf877cff.ee57f31d.js => cf877cff.06db9245.js} | 2 +- assets/js/{d07ad772.1a568f07.js => d07ad772.4ed10499.js} | 2 +- assets/js/{d3540d59.2377760d.js => d3540d59.34df5196.js} | 2 +- assets/js/{d4446569.ddfa5556.js => d4446569.39c2daf1.js} | 2 +- assets/js/{d49884c9.d35742e3.js => d49884c9.9a4dd072.js} | 2 +- assets/js/{d4c8693b.3138b0b0.js => d4c8693b.2b550467.js} | 2 +- assets/js/{d589d3a7.4f509987.js => d589d3a7.5a3a9b0b.js} | 2 +- assets/js/{d6188fd4.1f2e6f70.js => d6188fd4.a07234ea.js} | 2 +- assets/js/{d6b4b60c.6634bc76.js => d6b4b60c.010a242a.js} | 2 +- assets/js/{d7067606.16a3de8b.js => d7067606.0c33c4b9.js} | 2 +- assets/js/{d8037f4c.6bb564c4.js => d8037f4c.aa4c87e4.js} | 2 +- assets/js/{d8ff000f.70099734.js => d8ff000f.9d93ba36.js} | 2 +- assets/js/{d9523c62.e016ee1c.js => d9523c62.b56bad2f.js} | 2 +- assets/js/{db6a6f31.26f93eaf.js => db6a6f31.8f99dbe0.js} | 2 +- assets/js/{dbf2bcb3.ae27c30d.js => dbf2bcb3.364cf064.js} | 2 +- assets/js/{dc9a99e0.ea062c13.js => dc9a99e0.0ea91606.js} | 2 +- assets/js/{e126d786.759e384a.js => e126d786.f6d45879.js} | 2 +- assets/js/{e196b408.2a245732.js => e196b408.456456b5.js} | 2 +- assets/js/{e1b8bb84.e50032b6.js => e1b8bb84.3cc0d0de.js} | 2 +- assets/js/{e29eb381.a4b8dac7.js => e29eb381.53f21514.js} | 2 +- assets/js/{e2e51976.13362052.js => e2e51976.c3c8fc60.js} | 2 +- assets/js/{e347e63a.76738bdd.js => e347e63a.0915f118.js} | 2 +- assets/js/{e39283a8.d750a1ca.js => e39283a8.e3256bf2.js} | 2 +- assets/js/{e45c611c.444f2ef3.js => e45c611c.55637c17.js} | 2 +- assets/js/{e4c5fdc3.fd7ca642.js => e4c5fdc3.5ba1ee13.js} | 2 +- assets/js/{e5d0e3cb.97145ef4.js => e5d0e3cb.ca7ccaf8.js} | 2 +- assets/js/{e5d7b215.323d517e.js => e5d7b215.47184428.js} | 2 +- assets/js/{e617c97b.0098ac60.js => e617c97b.0f60a620.js} | 2 +- assets/js/{e63ebe23.2721bbb3.js => e63ebe23.c78c4380.js} | 2 +- assets/js/{e6858589.e2f7fe76.js => e6858589.58fb90f0.js} | 2 +- assets/js/{e688cd7e.1765bc4b.js => e688cd7e.b87d4ac1.js} | 2 +- assets/js/{e68b092b.3992b7f7.js => e68b092b.792b0f23.js} | 2 +- assets/js/{e7672013.4e9b3ab1.js => e7672013.c76f00ef.js} | 2 +- assets/js/{e7ffb4b4.b2a8e665.js => e7ffb4b4.60104518.js} | 2 +- assets/js/{e806c7bf.efbffd86.js => e806c7bf.31b41a0d.js} | 2 +- assets/js/{e91daeb9.8678688d.js => e91daeb9.d0fbb140.js} | 2 +- assets/js/{eaa287f0.7cc793f0.js => eaa287f0.a44a681c.js} | 2 +- assets/js/{eb333c39.bd942a0d.js => eb333c39.5a60d0b2.js} | 2 +- assets/js/{eca0cf35.451f4735.js => eca0cf35.367d84d2.js} | 2 +- assets/js/{ece9cf29.f9ce14a9.js => ece9cf29.df346d6b.js} | 2 +- assets/js/{ed0c0463.686f4c9e.js => ed0c0463.89bcbb2f.js} | 2 +- assets/js/{eec7caa6.aad4a995.js => eec7caa6.63014402.js} | 2 +- assets/js/{f07f4757.db4c0239.js => f07f4757.59bdbfef.js} | 2 +- assets/js/{f2710c27.d98f0418.js => f2710c27.506e278f.js} | 2 +- assets/js/{f309eabc.0c1b1123.js => f309eabc.5e793aef.js} | 2 +- assets/js/{f48e2589.b7e57141.js => f48e2589.03716c7f.js} | 2 +- assets/js/{f4e1d1ba.fac9d2e7.js => f4e1d1ba.b8330e7b.js} | 2 +- assets/js/{f5b0a435.816e2b9e.js => f5b0a435.dab0a149.js} | 2 +- assets/js/{f7c03581.e790e2e9.js => f7c03581.f154556e.js} | 2 +- assets/js/{f9063551.01cab4f0.js => f9063551.127e931e.js} | 2 +- assets/js/{f94b062c.e77a6f79.js => f94b062c.a92d86b1.js} | 2 +- assets/js/{f9511b3d.2f02d562.js => f9511b3d.606bb160.js} | 2 +- assets/js/{f9af357c.dd0a6e95.js => f9af357c.7717f183.js} | 2 +- assets/js/{fa1dd05c.c3d8a378.js => fa1dd05c.c6180736.js} | 2 +- assets/js/{fa41c0e9.62291ed9.js => fa41c0e9.852637a4.js} | 2 +- assets/js/{fe153c07.af7323d0.js => fe153c07.368664ec.js} | 2 +- .../{runtime~main.7bb6db3c.js => runtime~main.a29417e8.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/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 ++-- 766 files changed, 1531 insertions(+), 1531 deletions(-) rename assets/js/{01fe3043.9fc68b60.js => 01fe3043.b722dfb6.js} (99%) rename assets/js/{029c6d75.34cc9a73.js => 029c6d75.903e79a5.js} (99%) rename assets/js/{02c5a8b1.77711b74.js => 02c5a8b1.68048805.js} (99%) rename assets/js/{0343976d.3e3be5ef.js => 0343976d.0dc24357.js} (98%) rename assets/js/{0370fbfb.81068cea.js => 0370fbfb.a59bfdcd.js} (99%) rename assets/js/{03abab96.1f8b34ea.js => 03abab96.0060c15e.js} (98%) rename assets/js/{03c886f6.45a05f02.js => 03c886f6.4fbdf0ac.js} (99%) rename assets/js/{05e8cfc0.50d9e5fd.js => 05e8cfc0.8fa218cc.js} (98%) rename assets/js/{05fed6b1.5db9e3a1.js => 05fed6b1.f422f54a.js} (99%) rename assets/js/{06c02cc7.6f61e4dd.js => 06c02cc7.eee16367.js} (98%) rename assets/js/{07623f9a.21183fdc.js => 07623f9a.cdea6839.js} (99%) rename assets/js/{07666c14.9aceff08.js => 07666c14.aec3a10d.js} (98%) rename assets/js/{077a13b8.76a36fb7.js => 077a13b8.9e4db38f.js} (99%) rename assets/js/{079b0d3e.d9e3d7f8.js => 079b0d3e.3179f033.js} (99%) rename assets/js/{07c49ebd.3ead5716.js => 07c49ebd.04705fa2.js} (99%) rename assets/js/{085c135f.52279798.js => 085c135f.c4f91d04.js} (99%) rename assets/js/{08fe23a4.2dec6eeb.js => 08fe23a4.e92b4838.js} (96%) rename assets/js/{0a57d896.22dde59a.js => 0a57d896.9763be6f.js} (99%) rename assets/js/{0cb7e976.3c43838b.js => 0cb7e976.f6ed1648.js} (99%) rename assets/js/{0d7bb119.9167846c.js => 0d7bb119.d4075bc3.js} (98%) rename assets/js/{0db009bb.5a41a9e3.js => 0db009bb.88754719.js} (97%) rename assets/js/{0db959c8.cd0b2ed7.js => 0db959c8.19be7258.js} (99%) rename assets/js/{0df2ba32.c73ffdf3.js => 0df2ba32.4d5523d8.js} (98%) rename assets/js/{0e5befdb.9bb42ee8.js => 0e5befdb.adfcf147.js} (99%) rename assets/js/{0ef60658.3a8223fb.js => 0ef60658.3a0dda98.js} (99%) rename assets/js/{0fd21208.cef60eb6.js => 0fd21208.c7e0a6a1.js} (96%) rename assets/js/{102de343.cac6183f.js => 102de343.ac9aff92.js} (99%) rename assets/js/{107b7a36.67eb69dc.js => 107b7a36.ef8bab33.js} (98%) rename assets/js/{107d11ee.617e845b.js => 107d11ee.6b209a8d.js} (98%) rename assets/js/{12d3ef9e.2316a90f.js => 12d3ef9e.e1898768.js} (99%) rename assets/js/{136c1ee9.ee344fe1.js => 136c1ee9.1431f6c1.js} (99%) rename assets/js/{13b4aeb1.f687627c.js => 13b4aeb1.40ffa096.js} (98%) rename assets/js/{1428bdad.6eaa2756.js => 1428bdad.2f645659.js} (99%) rename assets/js/{143f7888.f3942f77.js => 143f7888.1d5adaec.js} (99%) rename assets/js/{15a79915.33beb644.js => 15a79915.be719ff6.js} (99%) rename assets/js/{15b5a907.2688abf0.js => 15b5a907.3d50e40d.js} (99%) rename assets/js/{16017aa6.3eccad0d.js => 16017aa6.a22be57e.js} (99%) rename assets/js/{16565e6a.94dbe306.js => 16565e6a.085e15ac.js} (99%) rename assets/js/{17518879.37f744be.js => 17518879.ea89b826.js} (99%) rename assets/js/{17cca601.007c3177.js => 17cca601.e8423ab3.js} (99%) rename assets/js/{18100524.fb2d6eb2.js => 18100524.2a11f212.js} (99%) rename assets/js/{1891fd2b.bc507d40.js => 1891fd2b.175c467d.js} (99%) rename assets/js/{18d6c9c9.9b1b6d63.js => 18d6c9c9.b0c01362.js} (99%) rename assets/js/{1aa05129.a3079b3b.js => 1aa05129.c0cd2084.js} (98%) rename assets/js/{1af245cd.c56b680a.js => 1af245cd.d7e67aae.js} (99%) rename assets/js/{1b1927f4.569471ed.js => 1b1927f4.a9a56397.js} (98%) rename assets/js/{1ba75d10.15824987.js => 1ba75d10.d2fc3080.js} (99%) rename assets/js/{1ca907c0.b2e2ea24.js => 1ca907c0.880728de.js} (98%) rename assets/js/{1d20a4b3.86bf69c5.js => 1d20a4b3.7b84c748.js} (99%) rename assets/js/{1d703573.c3571e4c.js => 1d703573.6488b685.js} (97%) rename assets/js/{1e2c5f46.b48d6e58.js => 1e2c5f46.def37f02.js} (98%) rename assets/js/{1e6ec01e.a9f97779.js => 1e6ec01e.79a26d94.js} (99%) rename assets/js/{1e7fe27e.10e1b4b0.js => 1e7fe27e.d543f284.js} (99%) rename assets/js/{1ea13486.8e8b73ef.js => 1ea13486.621658df.js} (98%) rename assets/js/{1edb88e5.9b4e4601.js => 1edb88e5.c186a972.js} (99%) rename assets/js/{1f5af0f2.b23e918f.js => 1f5af0f2.1e16655c.js} (98%) rename assets/js/{1f5e9707.bd784f60.js => 1f5e9707.cb48452a.js} (99%) rename assets/js/{2014e4e3.9a25270f.js => 2014e4e3.f5c34a4b.js} (98%) rename assets/js/{20540af3.bc6f4eb1.js => 20540af3.7b8b47f6.js} (99%) rename assets/js/{21637dff.cfa95698.js => 21637dff.bc0d8785.js} (99%) rename assets/js/{21a7a3b0.e2584029.js => 21a7a3b0.98695aa2.js} (99%) rename assets/js/{21cde469.2dda92b3.js => 21cde469.42de3ab5.js} (99%) rename assets/js/{22e1e32f.46a87359.js => 22e1e32f.a63c9c7d.js} (99%) rename assets/js/{232afa3a.6102f5c2.js => 232afa3a.4989b07d.js} (98%) rename assets/js/{2355609d.ec196a8f.js => 2355609d.3ad1d9e5.js} (98%) rename assets/js/{23794275.be36c6f0.js => 23794275.2d3cafaf.js} (99%) rename assets/js/{23a8ac29.6f8e7fa6.js => 23a8ac29.fef39a38.js} (99%) rename assets/js/{23f642f2.eb057b4d.js => 23f642f2.702af88f.js} (99%) rename assets/js/{242d99d9.ff085183.js => 242d99d9.65e7903b.js} (97%) rename assets/js/{24ac61c7.0594428c.js => 24ac61c7.56754f4a.js} (96%) rename assets/js/{24aca886.7f44594c.js => 24aca886.067e7bc9.js} (99%) rename assets/js/{25d4129e.57911023.js => 25d4129e.0452c424.js} (99%) rename assets/js/{263ebc7a.fd45594c.js => 263ebc7a.ab66a253.js} (99%) rename assets/js/{26662da3.c3e74a31.js => 26662da3.fe57afd5.js} (99%) rename assets/js/{26a27afb.ecb27e90.js => 26a27afb.f2ee3b29.js} (99%) rename assets/js/{27258a7d.11b80646.js => 27258a7d.c02372c5.js} (99%) rename assets/js/{27b414e3.20ddf17d.js => 27b414e3.a918f7e4.js} (99%) rename assets/js/{28c12eaf.f79d3873.js => 28c12eaf.0bf95a09.js} (99%) rename assets/js/{2917b31e.4ec91853.js => 2917b31e.f9c0b568.js} (99%) rename assets/js/{29a6c1ba.be7c1a69.js => 29a6c1ba.771a3fc1.js} (99%) rename assets/js/{29cf2ad6.e5209db4.js => 29cf2ad6.f26d1860.js} (99%) rename assets/js/{2b26025e.a2d49345.js => 2b26025e.2350cefd.js} (97%) rename assets/js/{2bbfc5d5.b4e123c4.js => 2bbfc5d5.545fc5e5.js} (99%) rename assets/js/{2d02c83c.df37da76.js => 2d02c83c.42480db1.js} (98%) rename assets/js/{2d4548df.87e9f636.js => 2d4548df.5485b326.js} (99%) rename assets/js/{2e25c87f.ea5ae136.js => 2e25c87f.05446db0.js} (99%) rename assets/js/{2e301473.3cc314c9.js => 2e301473.e6e2c4aa.js} (99%) rename assets/js/{2ef99682.a4397b07.js => 2ef99682.5ea187f2.js} (99%) rename assets/js/{2f36012a.6f491d09.js => 2f36012a.16b48290.js} (98%) rename assets/js/{30940d42.4f0f3c44.js => 30940d42.e7f62cec.js} (99%) rename assets/js/{31b4e903.04610a44.js => 31b4e903.6bbd747e.js} (97%) rename assets/js/{323a980a.6b82ac7e.js => 323a980a.13853cf0.js} (98%) rename assets/js/{332827b4.d4c1e857.js => 332827b4.f5ff9c8a.js} (98%) rename assets/js/{346bcb92.89b2ce95.js => 346bcb92.16595548.js} (99%) rename assets/js/{354a9b78.cedd99eb.js => 354a9b78.46c818e8.js} (98%) rename assets/js/{366cfce3.4f5e8a84.js => 366cfce3.072044f3.js} (99%) rename assets/js/{36ddade1.e248315d.js => 36ddade1.52451906.js} (97%) rename assets/js/{379bfe51.7edce05a.js => 379bfe51.ae5ebb8e.js} (99%) rename assets/js/{380575ae.cb57eedc.js => 380575ae.0fb3b47d.js} (99%) rename assets/js/{38317547.f454350d.js => 38317547.a1b9180d.js} (96%) rename assets/js/{38cf1c7a.c56a066d.js => 38cf1c7a.01e4fa32.js} (99%) rename assets/js/{394f3211.60a413eb.js => 394f3211.81f00e53.js} (99%) rename assets/js/{3b486936.410100a2.js => 3b486936.e4e39654.js} (97%) rename assets/js/{3d0eb74d.c0a1bbde.js => 3d0eb74d.2b99da9d.js} (99%) rename assets/js/{3d2d0a86.82169c25.js => 3d2d0a86.49c0e414.js} (99%) rename assets/js/{3f944aba.83281771.js => 3f944aba.3c25cf0e.js} (98%) rename assets/js/{400ddbbb.82e55cef.js => 400ddbbb.9a45cf17.js} (99%) rename assets/js/{4194805f.6b3b89b3.js => 4194805f.a49fe3a4.js} (99%) rename assets/js/{471c3e37.2a377d4d.js => 471c3e37.93d9c059.js} (99%) rename assets/js/{48fde361.1f0fc197.js => 48fde361.98272508.js} (99%) rename assets/js/{4a060504.83af7d17.js => 4a060504.2f73632b.js} (99%) rename assets/js/{4a07aaf0.ac98ae89.js => 4a07aaf0.9163f54f.js} (98%) rename assets/js/{4a2da18c.4eb1119f.js => 4a2da18c.2de5b1b3.js} (98%) rename assets/js/{4aab8b8c.89b3df88.js => 4aab8b8c.7218bae3.js} (99%) rename assets/js/{4bdafdff.73a284a0.js => 4bdafdff.0a931b29.js} (99%) rename assets/js/{4c5bf49d.4ac6e79a.js => 4c5bf49d.a481b861.js} (99%) rename assets/js/{4c7f7507.c8dd7aab.js => 4c7f7507.02676f01.js} (99%) rename assets/js/{4d00e03a.9dff7708.js => 4d00e03a.91ddc8d5.js} (99%) rename assets/js/{4d049718.bd40789e.js => 4d049718.73044c16.js} (99%) rename assets/js/{4d68b066.ea6539f6.js => 4d68b066.83f4dcfb.js} (98%) rename assets/js/{4dd5816e.1347aa25.js => 4dd5816e.ea996778.js} (99%) rename assets/js/{4dfeb783.faf621ba.js => 4dfeb783.f77b3a45.js} (99%) rename assets/js/{4e1a0951.3f9b7190.js => 4e1a0951.d5de8cab.js} (99%) rename assets/js/{4e73bd72.3b18a39d.js => 4e73bd72.8da00f07.js} (96%) rename assets/js/{4f30448a.cc668b1d.js => 4f30448a.e44fb11b.js} (99%) rename assets/js/{4f4b6633.f4ad5c07.js => 4f4b6633.4ebd402a.js} (99%) rename assets/js/{4f59166d.a1b41e48.js => 4f59166d.41f72369.js} (99%) rename assets/js/{4f6c3156.634f36b4.js => 4f6c3156.4814e7e0.js} (99%) rename assets/js/{50122f86.e7054e4a.js => 50122f86.0f469e64.js} (98%) rename assets/js/{504e6c2d.cfc4398d.js => 504e6c2d.47ec9159.js} (99%) rename assets/js/{509d2004.714400f3.js => 509d2004.1a6cb1b3.js} (99%) rename assets/js/{5285d58e.92cac4ae.js => 5285d58e.a659173f.js} (99%) rename assets/js/{528fe65e.c60be34d.js => 528fe65e.722571e6.js} (99%) rename assets/js/{54c144e4.9c598b07.js => 54c144e4.bb6063dc.js} (96%) rename assets/js/{54ca8693.de282c9d.js => 54ca8693.d08449f0.js} (98%) rename assets/js/{55c77f1e.00046a46.js => 55c77f1e.6554dceb.js} (98%) rename assets/js/{56279b5e.9367e8fe.js => 56279b5e.668f312e.js} (99%) rename assets/js/{565a5567.249b1f26.js => 565a5567.933d5222.js} (98%) rename assets/js/{56af72f6.5b19550c.js => 56af72f6.e60a700d.js} (99%) rename assets/js/{5792f9ba.1f23575a.js => 5792f9ba.00b9b662.js} (98%) rename assets/js/{579cc8d4.ed347d2a.js => 579cc8d4.1da1a812.js} (98%) rename assets/js/{57f5c28c.6e73b6ce.js => 57f5c28c.6aacba73.js} (99%) rename assets/js/{5881f7ec.00fefab5.js => 5881f7ec.9163213f.js} (99%) rename assets/js/{58d52345.57520c92.js => 58d52345.26ba55c3.js} (97%) rename assets/js/{58e6b30f.6820b216.js => 58e6b30f.2faed412.js} (99%) rename assets/js/{5945e8b0.e70e6fa1.js => 5945e8b0.efe55108.js} (99%) rename assets/js/{59b1a96c.c8c5d980.js => 59b1a96c.4b55b1e2.js} (97%) rename assets/js/{5a9b411c.ce6f95a4.js => 5a9b411c.559a6713.js} (99%) rename assets/js/{5bc7272e.0771ddb5.js => 5bc7272e.980951c9.js} (99%) rename assets/js/{5d7590c2.d21d7c9f.js => 5d7590c2.bc73a967.js} (98%) rename assets/js/{5dde70bf.fcf84c6a.js => 5dde70bf.b5740b86.js} (99%) rename assets/js/{5e21a9be.e8721d31.js => 5e21a9be.b6d9b713.js} (99%) rename assets/js/{5e352ef4.7431f3bd.js => 5e352ef4.cec79076.js} (99%) rename assets/js/{5e457383.cd22f35c.js => 5e457383.24cd44b0.js} (98%) rename assets/js/{5ec7a7fe.75d547c0.js => 5ec7a7fe.9f7d2515.js} (99%) rename assets/js/{5ececfab.321e03dd.js => 5ececfab.81c29f92.js} (99%) rename assets/js/{5fa4a5b6.4a59bbf6.js => 5fa4a5b6.0c5693e2.js} (99%) rename assets/js/{5ffc8074.41ae9a58.js => 5ffc8074.382b4640.js} (99%) rename assets/js/{606959d6.12b37f8d.js => 606959d6.2d95a4c6.js} (99%) rename assets/js/{60d99771.6eee9b87.js => 60d99771.ac4342ef.js} (98%) rename assets/js/{610e7425.d2835569.js => 610e7425.22b083d8.js} (99%) rename assets/js/{612b773e.7d6b0229.js => 612b773e.e479b012.js} (96%) rename assets/js/{61595218.74330fc8.js => 61595218.ebfdff1a.js} (99%) rename assets/js/{617523b3.88a4d717.js => 617523b3.79ae2a0c.js} (99%) rename assets/js/{61c7d915.ddc67bf7.js => 61c7d915.0a2b168b.js} (98%) rename assets/js/{623b6c78.bc73ad97.js => 623b6c78.d7c4e3d8.js} (99%) rename assets/js/{64536e1a.07bf472c.js => 64536e1a.e0906f5a.js} (99%) rename assets/js/{64947e00.ed002f1f.js => 64947e00.ec66addf.js} (99%) rename assets/js/{652c74f1.3e38ddd7.js => 652c74f1.6359bb26.js} (99%) rename assets/js/{65b8d1d1.8d1b90a0.js => 65b8d1d1.d8e12cac.js} (99%) rename assets/js/{673df5d6.895ad17e.js => 673df5d6.a9b22576.js} (99%) rename assets/js/{68b7d615.07386ae0.js => 68b7d615.9c5c0e30.js} (99%) rename assets/js/{68e30702.fe37ea89.js => 68e30702.5028a35e.js} (98%) rename assets/js/{69f2ab1f.051152f6.js => 69f2ab1f.8ca20958.js} (99%) rename assets/js/{6a8c9872.3340519d.js => 6a8c9872.7ccea129.js} (99%) rename assets/js/{6ad31330.27875216.js => 6ad31330.e6d3127b.js} (97%) rename assets/js/{6c124661.7cbe5021.js => 6c124661.ef09a451.js} (98%) rename assets/js/{6c14a231.d3c7ec0b.js => 6c14a231.1d305f75.js} (99%) rename assets/js/{6c4340be.1aaa0aca.js => 6c4340be.df1dad05.js} (99%) rename assets/js/{6c6ce37c.00a01a79.js => 6c6ce37c.9f1a930b.js} (97%) rename assets/js/{6cfcfcfb.538269ec.js => 6cfcfcfb.d44b9f3a.js} (99%) rename assets/js/{6d89025c.0ed36bbc.js => 6d89025c.2bba48c9.js} (99%) rename assets/js/{6efd6ec9.054a55e6.js => 6efd6ec9.7ee75f12.js} (99%) rename assets/js/{6fe30f11.63909169.js => 6fe30f11.1772048a.js} (98%) rename assets/js/{71a56230.30d486bb.js => 71a56230.2f5cd36c.js} (97%) rename assets/js/{72be5fd7.72da73d5.js => 72be5fd7.5f11d860.js} (99%) rename assets/js/{72d0dc3a.8a2fadd5.js => 72d0dc3a.757595fe.js} (97%) rename assets/js/{741df2ae.d7ee228b.js => 741df2ae.8def9ec7.js} (99%) rename assets/js/{74383bd8.36d2c5e5.js => 74383bd8.52f7baf7.js} (99%) rename assets/js/{7515d7ec.3c6e0fa6.js => 7515d7ec.cd92088e.js} (99%) rename assets/js/{756c6ac7.182b31ca.js => 756c6ac7.c578852e.js} (99%) rename assets/js/{75cc8326.435bc032.js => 75cc8326.3c8456bf.js} (99%) rename assets/js/{766e1cc8.007f2971.js => 766e1cc8.5884e667.js} (99%) rename assets/js/{767c28af.ec7dc3fc.js => 767c28af.076047b9.js} (99%) rename assets/js/{77cdcd82.979607ae.js => 77cdcd82.121eed95.js} (97%) rename assets/js/{7810a993.263785f9.js => 7810a993.16409b83.js} (99%) rename assets/js/{78619623.5a6df041.js => 78619623.2a48f5b2.js} (99%) rename assets/js/{78da31a1.8e7ba28c.js => 78da31a1.81a56c02.js} (99%) rename assets/js/{7afb60b1.a34d9d6f.js => 7afb60b1.1b724298.js} (99%) rename assets/js/{7b54f5d5.b5df9ba2.js => 7b54f5d5.ad75730f.js} (99%) rename assets/js/{7bf967bc.02928b46.js => 7bf967bc.76cb6139.js} (98%) rename assets/js/{7c27e34c.c005f810.js => 7c27e34c.19b3c022.js} (95%) rename assets/js/{7e507331.672c2963.js => 7e507331.604dcbe9.js} (98%) rename assets/js/{7e63a40e.bc402124.js => 7e63a40e.e9c65e4c.js} (98%) rename assets/js/{7ee46e43.af9426ef.js => 7ee46e43.ac809c54.js} (98%) rename assets/js/{820db038.bdb67856.js => 820db038.336d5a20.js} (99%) rename assets/js/{822cd419.4bbdece7.js => 822cd419.eec8322d.js} (98%) rename assets/js/{82395e72.32f48466.js => 82395e72.d158cad6.js} (99%) rename assets/js/{8299d165.5a2348ca.js => 8299d165.45757bd5.js} (99%) rename assets/js/{843ebfb4.462347e3.js => 843ebfb4.8680fd03.js} (99%) rename assets/js/{85339969.0793324f.js => 85339969.cf5cbbcf.js} (99%) rename assets/js/{859fcda7.614c1383.js => 859fcda7.6f4e9cfc.js} (97%) rename assets/js/{85c72337.1def6368.js => 85c72337.68dbbe79.js} (99%) rename assets/js/{87089bce.e0da2805.js => 87089bce.c45cefa8.js} (99%) rename assets/js/{8913b51a.1b840764.js => 8913b51a.099434fd.js} (98%) rename assets/js/{89cae3a7.26a332e9.js => 89cae3a7.f2f58bf0.js} (99%) rename assets/js/{89ed63c8.cdb311ab.js => 89ed63c8.dab6893e.js} (99%) rename assets/js/{8b6bafea.c0ebbd9d.js => 8b6bafea.d38cc5d5.js} (98%) rename assets/js/{8bf32d27.5148b85d.js => 8bf32d27.2de9f795.js} (99%) rename assets/js/{8c95fc16.191afaf6.js => 8c95fc16.8c929c5b.js} (99%) rename assets/js/{8d81badd.81c8237f.js => 8d81badd.6701e780.js} (99%) rename assets/js/{8f7abfe1.7d38c4e5.js => 8f7abfe1.0827e6c1.js} (99%) rename assets/js/{8f7fa040.12aee849.js => 8f7fa040.19aa9fff.js} (99%) rename assets/js/{8f951ce3.686bd959.js => 8f951ce3.44fe12e6.js} (98%) rename assets/js/{8f967659.6820bbdd.js => 8f967659.2a8b80c0.js} (98%) rename assets/js/{9000b231.e4f1d685.js => 9000b231.2d7f009f.js} (98%) rename assets/js/{9073923c.2450bdcb.js => 9073923c.14428e5a.js} (98%) rename assets/js/{90e0b7fd.d1dbb559.js => 90e0b7fd.db56516a.js} (99%) rename assets/js/{9206a32f.5c74cb1b.js => 9206a32f.5c4bd34f.js} (99%) rename assets/js/{9279cea7.fe498c74.js => 9279cea7.308af6f9.js} (99%) rename assets/js/{947f2c39.ba2fa99a.js => 947f2c39.ab8670a7.js} (98%) rename assets/js/{950394a4.63eb0f08.js => 950394a4.ed70f17c.js} (99%) rename assets/js/{95576100.21e23958.js => 95576100.6ede392b.js} (99%) rename assets/js/{9664ee55.db3a0eb9.js => 9664ee55.dfc7699e.js} (99%) rename assets/js/{96877411.c0200494.js => 96877411.4913f2de.js} (99%) rename assets/js/{9749ab4a.7572e404.js => 9749ab4a.ddfa782f.js} (99%) rename assets/js/{976f6afc.a654a515.js => 976f6afc.503f4678.js} (99%) rename assets/js/{9953ecde.4888f0d5.js => 9953ecde.5bddb47b.js} (98%) rename assets/js/{9bd507da.4540c36c.js => 9bd507da.e9692c43.js} (98%) rename assets/js/{9d336ee4.15d9be2f.js => 9d336ee4.72a6efbc.js} (99%) rename assets/js/{9d9f8394.ec32e8ef.js => 9d9f8394.e9ef5f63.js} (97%) rename assets/js/{9f0ecd2e.1a01299d.js => 9f0ecd2e.f5db31e4.js} (98%) rename assets/js/{a0bf4a5f.e3ac7f51.js => a0bf4a5f.dcfbd033.js} (98%) rename assets/js/{a13f3cdc.600c339c.js => a13f3cdc.a5356667.js} (99%) rename assets/js/{a16ee953.b2b49229.js => a16ee953.0fbc4b46.js} (99%) rename assets/js/{a1e3d512.5f53de34.js => a1e3d512.07ea288b.js} (99%) rename assets/js/{a23a5b68.250a7b15.js => a23a5b68.35c6cfe4.js} (99%) rename assets/js/{a264d631.3aec4aef.js => a264d631.8c2e8f25.js} (99%) rename assets/js/{a27ea030.1e3d8131.js => a27ea030.421025a3.js} (98%) rename assets/js/{a27f6be0.f4c630d8.js => a27f6be0.93950472.js} (98%) rename assets/js/{a28aff23.1711f5a4.js => a28aff23.d95ba250.js} (99%) rename assets/js/{a2d3d8d2.8e3e1cb6.js => a2d3d8d2.6dcfb1a2.js} (99%) rename assets/js/{a30fd8ca.50645db0.js => a30fd8ca.615ed318.js} (99%) rename assets/js/{a320b509.ee5d6717.js => a320b509.7ab18136.js} (98%) rename assets/js/{a3a193a6.e6f82b19.js => a3a193a6.66147a15.js} (98%) rename assets/js/{a55b0daf.8b9c7c4f.js => a55b0daf.d5861c2c.js} (99%) rename assets/js/{a9125b44.ea36bda7.js => a9125b44.2e25c318.js} (99%) rename assets/js/{a91c1a62.2f51963a.js => a91c1a62.151c5c44.js} (97%) rename assets/js/{a95c9e82.74ac082a.js => a95c9e82.85a1f0cf.js} (99%) rename assets/js/{a99e9943.760f22fa.js => a99e9943.6c8a6d61.js} (98%) rename assets/js/{a9bc4f03.fa1f1757.js => a9bc4f03.b4a3dfa1.js} (99%) rename assets/js/{aa52484c.67b98c1e.js => aa52484c.74012053.js} (98%) rename assets/js/{aa5b6080.8403baf7.js => aa5b6080.5bf1d237.js} (99%) rename assets/js/{aa675676.60b0926d.js => aa675676.61394c21.js} (99%) rename assets/js/{aba5bf07.035001c1.js => aba5bf07.2edcb8ab.js} (99%) rename assets/js/{ac8293fa.efbab152.js => ac8293fa.5590a3a2.js} (99%) rename assets/js/{acbaac14.212ed806.js => acbaac14.df94e672.js} (99%) rename assets/js/{ae0a12ed.5aab8eff.js => ae0a12ed.3ea7f2e0.js} (99%) rename assets/js/{aebf35b6.9e1d2104.js => aebf35b6.2c35a4e2.js} (99%) rename assets/js/{b06c439f.1e48dcce.js => b06c439f.a328d225.js} (99%) rename assets/js/{b0ed7ea5.6e1fd2a9.js => b0ed7ea5.e78cbc24.js} (99%) rename assets/js/{b103c05a.abdaf47c.js => b103c05a.3f1db171.js} (99%) rename assets/js/{b26a5b84.df74297c.js => b26a5b84.70df5a5a.js} (99%) rename assets/js/{b2d9540a.8b170ae8.js => b2d9540a.94cb79db.js} (99%) rename assets/js/{b35d1284.f62c70b4.js => b35d1284.29c39c4b.js} (98%) rename assets/js/{b370b50c.ded65cc0.js => b370b50c.020852bb.js} (99%) rename assets/js/{b42f5805.3e26017e.js => b42f5805.c207b0b2.js} (99%) rename assets/js/{b4657038.0a64f0ff.js => b4657038.78fb71e5.js} (98%) rename assets/js/{b4aea2ce.b8c1c91c.js => b4aea2ce.e042c4be.js} (98%) rename assets/js/{b5d0ac54.06097821.js => b5d0ac54.0c090973.js} (99%) rename assets/js/{b5d32d98.fb4df112.js => b5d32d98.f3319d03.js} (98%) rename assets/js/{b6722b03.c33ad6bb.js => b6722b03.706f9763.js} (99%) rename assets/js/{b6a6a31f.f3cfb108.js => b6a6a31f.f3a4b1ab.js} (98%) rename assets/js/{b7442939.f1dfeb88.js => b7442939.6e0e3185.js} (99%) rename assets/js/{b8487569.8aa4dd2e.js => b8487569.34de94db.js} (99%) rename assets/js/{b94a1068.989eaf9b.js => b94a1068.70ece279.js} (99%) rename assets/js/{b9d6d6e5.a0a8a034.js => b9d6d6e5.ed929d1d.js} (98%) rename assets/js/{b9ea999a.54ec31ba.js => b9ea999a.a642f64a.js} (99%) rename assets/js/{ba7653ad.5b47d0d7.js => ba7653ad.bbc1d3a3.js} (99%) rename assets/js/{bb5ef1b7.e0206554.js => bb5ef1b7.2c1da688.js} (99%) rename assets/js/{bb9fe7c3.5f6f8397.js => bb9fe7c3.fe26e692.js} (99%) rename assets/js/{bcb6471f.d7d64164.js => bcb6471f.e5fedff8.js} (99%) rename assets/js/{bcc01c83.aeb7afc4.js => bcc01c83.a8d43fe5.js} (99%) rename assets/js/{bd2c4a98.00d5dde8.js => bd2c4a98.96e2d1cb.js} (99%) rename assets/js/{bda39da3.3356cab1.js => bda39da3.42af0747.js} (98%) rename assets/js/{bdb33130.d803a9da.js => bdb33130.60d5e579.js} (99%) rename assets/js/{be1f0304.730884bb.js => be1f0304.e6b63afc.js} (99%) rename assets/js/{beccb025.30f90fdb.js => beccb025.0cf1609c.js} (98%) rename assets/js/{bf2a5963.2a3df866.js => bf2a5963.8d2652ff.js} (99%) rename assets/js/{c007fb39.7a129435.js => c007fb39.78d67697.js} (99%) rename assets/js/{c0fa6485.d13d334d.js => c0fa6485.5373e105.js} (98%) rename assets/js/{c10d4a63.f2de6ddf.js => c10d4a63.b22f5985.js} (99%) rename assets/js/{c1fe0282.5c47ead6.js => c1fe0282.e663460d.js} (99%) rename assets/js/{c275698c.738c0c33.js => c275698c.fc512c41.js} (99%) rename assets/js/{c329487f.e61d729d.js => c329487f.d022b7c1.js} (99%) rename assets/js/{c3701568.24a3bd1a.js => c3701568.5cb9c150.js} (98%) rename assets/js/{c4d37b36.e63e72c1.js => c4d37b36.ebe7ba67.js} (99%) rename assets/js/{c5fa393d.317dd843.js => c5fa393d.c9ae6aa6.js} (98%) rename assets/js/{c69dda99.24f7f4ac.js => c69dda99.7bed8d0f.js} (99%) rename assets/js/{c7a4caa1.437fdf09.js => c7a4caa1.d204f912.js} (98%) rename assets/js/{c7e7ae18.62df2119.js => c7e7ae18.8214a40d.js} (99%) rename assets/js/{c8bdc4df.e0efc303.js => c8bdc4df.390ff8eb.js} (98%) rename assets/js/{c933a311.383732ef.js => c933a311.12e46a4a.js} (99%) rename assets/js/{c953ec08.04b40a4d.js => c953ec08.044ba5e1.js} (99%) rename assets/js/{ca36df4d.7e867049.js => ca36df4d.94c47d62.js} (99%) rename assets/js/{caa79efa.851f28bb.js => caa79efa.53b67792.js} (99%) rename assets/js/{cb01db44.364564ce.js => cb01db44.57683fd3.js} (99%) rename assets/js/{cc08685c.00b229fc.js => cc08685c.e931f2d8.js} (99%) rename assets/js/{cc1c02fe.14b8c14a.js => cc1c02fe.f50e1ffd.js} (99%) rename assets/js/{cc1f18af.509da543.js => cc1f18af.993e0004.js} (99%) rename assets/js/{cd25a595.6427617e.js => cd25a595.cedacea9.js} (99%) rename assets/js/{cd30f404.d4883c0f.js => cd30f404.ad234e4d.js} (99%) rename assets/js/{cd699560.560b6c61.js => cd699560.3152ae70.js} (99%) rename assets/js/{cddcd4e6.b97b3b81.js => cddcd4e6.b0f5a7d8.js} (99%) rename assets/js/{ce95b17c.0f107b8a.js => ce95b17c.d0a613b9.js} (98%) rename assets/js/{cf877cff.ee57f31d.js => cf877cff.06db9245.js} (94%) rename assets/js/{d07ad772.1a568f07.js => d07ad772.4ed10499.js} (99%) rename assets/js/{d3540d59.2377760d.js => d3540d59.34df5196.js} (99%) rename assets/js/{d4446569.ddfa5556.js => d4446569.39c2daf1.js} (99%) rename assets/js/{d49884c9.d35742e3.js => d49884c9.9a4dd072.js} (99%) rename assets/js/{d4c8693b.3138b0b0.js => d4c8693b.2b550467.js} (98%) rename assets/js/{d589d3a7.4f509987.js => d589d3a7.5a3a9b0b.js} (97%) rename assets/js/{d6188fd4.1f2e6f70.js => d6188fd4.a07234ea.js} (98%) rename assets/js/{d6b4b60c.6634bc76.js => d6b4b60c.010a242a.js} (99%) rename assets/js/{d7067606.16a3de8b.js => d7067606.0c33c4b9.js} (99%) rename assets/js/{d8037f4c.6bb564c4.js => d8037f4c.aa4c87e4.js} (97%) rename assets/js/{d8ff000f.70099734.js => d8ff000f.9d93ba36.js} (99%) rename assets/js/{d9523c62.e016ee1c.js => d9523c62.b56bad2f.js} (99%) rename assets/js/{db6a6f31.26f93eaf.js => db6a6f31.8f99dbe0.js} (99%) rename assets/js/{dbf2bcb3.ae27c30d.js => dbf2bcb3.364cf064.js} (99%) rename assets/js/{dc9a99e0.ea062c13.js => dc9a99e0.0ea91606.js} (99%) rename assets/js/{e126d786.759e384a.js => e126d786.f6d45879.js} (99%) rename assets/js/{e196b408.2a245732.js => e196b408.456456b5.js} (98%) rename assets/js/{e1b8bb84.e50032b6.js => e1b8bb84.3cc0d0de.js} (99%) rename assets/js/{e29eb381.a4b8dac7.js => e29eb381.53f21514.js} (99%) rename assets/js/{e2e51976.13362052.js => e2e51976.c3c8fc60.js} (99%) rename assets/js/{e347e63a.76738bdd.js => e347e63a.0915f118.js} (99%) rename assets/js/{e39283a8.d750a1ca.js => e39283a8.e3256bf2.js} (99%) rename assets/js/{e45c611c.444f2ef3.js => e45c611c.55637c17.js} (99%) rename assets/js/{e4c5fdc3.fd7ca642.js => e4c5fdc3.5ba1ee13.js} (98%) rename assets/js/{e5d0e3cb.97145ef4.js => e5d0e3cb.ca7ccaf8.js} (99%) rename assets/js/{e5d7b215.323d517e.js => e5d7b215.47184428.js} (98%) rename assets/js/{e617c97b.0098ac60.js => e617c97b.0f60a620.js} (99%) rename assets/js/{e63ebe23.2721bbb3.js => e63ebe23.c78c4380.js} (99%) rename assets/js/{e6858589.e2f7fe76.js => e6858589.58fb90f0.js} (96%) rename assets/js/{e688cd7e.1765bc4b.js => e688cd7e.b87d4ac1.js} (99%) rename assets/js/{e68b092b.3992b7f7.js => e68b092b.792b0f23.js} (99%) rename assets/js/{e7672013.4e9b3ab1.js => e7672013.c76f00ef.js} (98%) rename assets/js/{e7ffb4b4.b2a8e665.js => e7ffb4b4.60104518.js} (97%) rename assets/js/{e806c7bf.efbffd86.js => e806c7bf.31b41a0d.js} (99%) rename assets/js/{e91daeb9.8678688d.js => e91daeb9.d0fbb140.js} (99%) rename assets/js/{eaa287f0.7cc793f0.js => eaa287f0.a44a681c.js} (99%) rename assets/js/{eb333c39.bd942a0d.js => eb333c39.5a60d0b2.js} (98%) rename assets/js/{eca0cf35.451f4735.js => eca0cf35.367d84d2.js} (99%) rename assets/js/{ece9cf29.f9ce14a9.js => ece9cf29.df346d6b.js} (99%) rename assets/js/{ed0c0463.686f4c9e.js => ed0c0463.89bcbb2f.js} (99%) rename assets/js/{eec7caa6.aad4a995.js => eec7caa6.63014402.js} (99%) rename assets/js/{f07f4757.db4c0239.js => f07f4757.59bdbfef.js} (99%) rename assets/js/{f2710c27.d98f0418.js => f2710c27.506e278f.js} (98%) rename assets/js/{f309eabc.0c1b1123.js => f309eabc.5e793aef.js} (99%) rename assets/js/{f48e2589.b7e57141.js => f48e2589.03716c7f.js} (97%) rename assets/js/{f4e1d1ba.fac9d2e7.js => f4e1d1ba.b8330e7b.js} (98%) rename assets/js/{f5b0a435.816e2b9e.js => f5b0a435.dab0a149.js} (99%) rename assets/js/{f7c03581.e790e2e9.js => f7c03581.f154556e.js} (99%) rename assets/js/{f9063551.01cab4f0.js => f9063551.127e931e.js} (99%) rename assets/js/{f94b062c.e77a6f79.js => f94b062c.a92d86b1.js} (99%) rename assets/js/{f9511b3d.2f02d562.js => f9511b3d.606bb160.js} (99%) rename assets/js/{f9af357c.dd0a6e95.js => f9af357c.7717f183.js} (99%) rename assets/js/{fa1dd05c.c3d8a378.js => fa1dd05c.c6180736.js} (99%) rename assets/js/{fa41c0e9.62291ed9.js => fa41c0e9.852637a4.js} (99%) rename assets/js/{fe153c07.af7323d0.js => fe153c07.368664ec.js} (99%) rename assets/js/{runtime~main.7bb6db3c.js => runtime~main.a29417e8.js} (61%) diff --git a/404.html b/404.html index 886fa327f..e784e422e 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.9fc68b60.js b/assets/js/01fe3043.b722dfb6.js similarity index 99% rename from assets/js/01fe3043.9fc68b60.js rename to assets/js/01fe3043.b722dfb6.js index c8168ed72..53478be68 100644 --- a/assets/js/01fe3043.9fc68b60.js +++ b/assets/js/01fe3043.b722dfb6.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 d(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"),"."))}d.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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 d(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"),"."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/029c6d75.34cc9a73.js b/assets/js/029c6d75.903e79a5.js similarity index 99% rename from assets/js/029c6d75.34cc9a73.js rename to assets/js/029c6d75.903e79a5.js index ae81339a6..76db36d2c 100644 --- a/assets/js/029c6d75.34cc9a73.js +++ b/assets/js/029c6d75.903e79a5.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.77711b74.js b/assets/js/02c5a8b1.68048805.js similarity index 99% rename from assets/js/02c5a8b1.77711b74.js rename to assets/js/02c5a8b1.68048805.js index 73c884f59..29cc9ad12 100644 --- a/assets/js/02c5a8b1.77711b74.js +++ b/assets/js/02c5a8b1.68048805.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.81068cea.js b/assets/js/0370fbfb.a59bfdcd.js similarity index 99% rename from assets/js/0370fbfb.81068cea.js rename to assets/js/0370fbfb.a59bfdcd.js index 6b32a7a56..2dea444bf 100644 --- a/assets/js/0370fbfb.81068cea.js +++ b/assets/js/0370fbfb.a59bfdcd.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.1f8b34ea.js b/assets/js/03abab96.0060c15e.js similarity index 98% rename from assets/js/03abab96.1f8b34ea.js rename to assets/js/03abab96.0060c15e.js index 024212fd6..6f6587bc4 100644 --- a/assets/js/03abab96.1f8b34ea.js +++ b/assets/js/03abab96.0060c15e.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.45a05f02.js b/assets/js/03c886f6.4fbdf0ac.js similarity index 99% rename from assets/js/03c886f6.45a05f02.js rename to assets/js/03c886f6.4fbdf0ac.js index 6f1bdf189..8a2aa85ed 100644 --- a/assets/js/03c886f6.45a05f02.js +++ b/assets/js/03c886f6.4fbdf0ac.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:()=>g,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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom annotations",permalink:"/docs/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function g(e){let{components:a,...n}=e;return(0,r.yg)(d,(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".'))}g.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:()=>g,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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom annotations",permalink:"/docs/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function g(e){let{components:a,...n}=e;return(0,r.yg)(d,(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".'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/05e8cfc0.50d9e5fd.js b/assets/js/05e8cfc0.8fa218cc.js similarity index 98% rename from assets/js/05e8cfc0.50d9e5fd.js rename to assets/js/05e8cfc0.8fa218cc.js index 558cfc4a6..0cab324bc 100644 --- a/assets/js/05e8cfc0.50d9e5fd.js +++ b/assets/js/05e8cfc0.8fa218cc.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5091],{3716:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>u,contentTitle:()=>l,default:()=>y,frontMatter:()=>o,metadata:()=>i,toc:()=>s});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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan",original_id:"query-plan"},sidebar:"version-4.0/docs",previous:{title:"Connecting security to your framework",permalink:"/docs/4.0/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/4.0/prefetch-method"}},u={},s=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],p={toc:s},d="wrapper";function 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:()=>u,contentTitle:()=>l,default:()=>y,frontMatter:()=>o,metadata:()=>i,toc:()=>s});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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"query-plan",title:"Query plan",sidebar_label:"Query plan",original_id:"query-plan"},sidebar:"version-4.0/docs",previous:{title:"Connecting security to your framework",permalink:"/docs/4.0/implementing-security"},next:{title:"Prefetching records",permalink:"/docs/4.0/prefetch-method"}},u={},s=[{value:"The problem",id:"the-problem",level:2},{value:"Fetching the query plan",id:"fetching-the-query-plan",level:2}],p={toc:s},d="wrapper";function 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.5db9e3a1.js b/assets/js/05fed6b1.f422f54a.js similarity index 99% rename from assets/js/05fed6b1.5db9e3a1.js rename to assets/js/05fed6b1.f422f54a.js index b0057c093..f33d39dfe 100644 --- a/assets/js/05fed6b1.5db9e3a1.js +++ b/assets/js/05fed6b1.f422f54a.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.6f61e4dd.js b/assets/js/06c02cc7.eee16367.js similarity index 98% rename from assets/js/06c02cc7.6f61e4dd.js rename to assets/js/06c02cc7.eee16367.js index 17c353fe1..bfd57f79a 100644 --- a/assets/js/06c02cc7.6f61e4dd.js +++ b/assets/js/06c02cc7.eee16367.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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([[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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/07623f9a.21183fdc.js b/assets/js/07623f9a.cdea6839.js similarity index 99% rename from assets/js/07623f9a.21183fdc.js rename to assets/js/07623f9a.cdea6839.js index 76a4b1da4..c0357c241 100644 --- a/assets/js/07623f9a.21183fdc.js +++ b/assets/js/07623f9a.cdea6839.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6925],{42562:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>s});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"},o=void 0,i={unversionedId:"symfony-bundle",id:"version-4.0/symfony-bundle",title:"Getting started with Symfony",description:"The GraphQLite bundle is compatible with Symfony 4.x and Symfony 5.x.",source:"@site/versioned_docs/version-4.0/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/4.0/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/symfony-bundle.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 d(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},y,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")," 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"},"{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>s});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"},o=void 0,i={unversionedId:"symfony-bundle",id:"version-4.0/symfony-bundle",title:"Getting started with Symfony",description:"The GraphQLite bundle is compatible with Symfony 4.x and Symfony 5.x.",source:"@site/versioned_docs/version-4.0/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/4.0/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/symfony-bundle.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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 d(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},y,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")," 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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.76a36fb7.js b/assets/js/077a13b8.9e4db38f.js similarity index 99% rename from assets/js/077a13b8.76a36fb7.js rename to assets/js/077a13b8.9e4db38f.js index f55a72acb..124d899ca 100644 --- a/assets/js/077a13b8.76a36fb7.js +++ b/assets/js/077a13b8.9e4db38f.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.d9e3d7f8.js b/assets/js/079b0d3e.3179f033.js similarity index 99% rename from assets/js/079b0d3e.d9e3d7f8.js rename to assets/js/079b0d3e.3179f033.js index d800e00ce..72ab242b8 100644 --- a/assets/js/079b0d3e.d9e3d7f8.js +++ b/assets/js/079b0d3e.3179f033.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.3ead5716.js b/assets/js/07c49ebd.04705fa2.js similarity index 99% rename from assets/js/07c49ebd.3ead5716.js rename to assets/js/07c49ebd.04705fa2.js index 8430318e2..1d54c8c86 100644 --- a/assets/js/07c49ebd.3ead5716.js +++ b/assets/js/07c49ebd.04705fa2.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8633],{37721:(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",original_id:"field-middlewares"},r=void 0,o={unversionedId:"field-middlewares",id:"version-4.1/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.1/field_middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/4.1/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/field_middlewares.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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,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([[8633],{37721:(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",original_id:"field-middlewares"},r=void 0,o={unversionedId:"field-middlewares",id:"version-4.1/field-middlewares",title:"Adding custom annotations with Field middlewares",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.1/field_middlewares.md",sourceDirName:".",slug:"/field-middlewares",permalink:"/docs/4.1/field-middlewares",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/field_middlewares.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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,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/085c135f.52279798.js b/assets/js/085c135f.c4f91d04.js similarity index 99% rename from assets/js/085c135f.52279798.js rename to assets/js/085c135f.c4f91d04.js index e2b56f48f..2a7d8675e 100644 --- a/assets/js/085c135f.52279798.js +++ b/assets/js/085c135f.c4f91d04.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 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 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=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=g({queryString:a,groupId:n}),[d,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??d;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:d}=(0,u.a_)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.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:p},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:()=>d});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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"version-4.3/docs",next:{title:"Getting Started",permalink:"/docs/4.3/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(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)(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 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 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=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=g({queryString:a,groupId:n}),[d,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??d;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:d}=(0,u.a_)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.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:p},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:()=>d});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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"version-4.3/docs",next:{title:"Getting Started",permalink:"/docs/4.3/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(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)(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.2dec6eeb.js b/assets/js/08fe23a4.e92b4838.js similarity index 96% rename from assets/js/08fe23a4.2dec6eeb.js rename to assets/js/08fe23a4.e92b4838.js index c2bb09ec8..06aaa03f8 100644 --- a/assets/js/08fe23a4.2dec6eeb.js +++ b/assets/js/08fe23a4.e92b4838.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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=[],p={toc:d},l="wrapper";function c(t){let{components:e,...n}=t;return(0,i.yg)(l,(0,a.A)({},p,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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=[],p={toc:d},l="wrapper";function c(t){let{components:e,...n}=t;return(0,i.yg)(l,(0,a.A)({},p,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.22dde59a.js b/assets/js/0a57d896.9763be6f.js similarity index 99% rename from assets/js/0a57d896.22dde59a.js rename to assets/js/0a57d896.9763be6f.js index c2a55ee64..7d56704a2 100644 --- a/assets/js/0a57d896.22dde59a.js +++ b/assets/js/0a57d896.9763be6f.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),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 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:()=>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",original_id:"error-handling"},s=void 0,u={unversionedId:"error-handling",id:"version-4.1/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-4.1/error_handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/4.1/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/error_handling.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling",original_id:"error-handling"},sidebar:"version-4.1/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/4.1/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/4.1/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function 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),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 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:()=>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",original_id:"error-handling"},s=void 0,u={unversionedId:"error-handling",id:"version-4.1/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-4.1/error_handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/4.1/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/error_handling.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling",original_id:"error-handling"},sidebar:"version-4.1/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/4.1/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/4.1/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function 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.3c43838b.js b/assets/js/0cb7e976.f6ed1648.js similarity index 99% rename from assets/js/0cb7e976.3c43838b.js rename to assets/js/0cb7e976.f6ed1648.js index a20308867..bc4089475 100644 --- a/assets/js/0cb7e976.3c43838b.js +++ b/assets/js/0cb7e976.f6ed1648.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.9167846c.js b/assets/js/0d7bb119.d4075bc3.js similarity index 98% rename from assets/js/0d7bb119.9167846c.js rename to assets/js/0d7bb119.d4075bc3.js index 40bd20bc4..6dee94983 100644 --- a/assets/js/0d7bb119.9167846c.js +++ b/assets/js/0d7bb119.d4075bc3.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.5a41a9e3.js b/assets/js/0db009bb.88754719.js similarity index 97% rename from assets/js/0db009bb.5a41a9e3.js rename to assets/js/0db009bb.88754719.js index 0774cab10..96563f6da 100644 --- a/assets/js/0db009bb.5a41a9e3.js +++ b/assets/js/0db009bb.88754719.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"version-4.3/docs",previous:{title:"GraphQLite",permalink:"/docs/4.3/"},next:{title:"Symfony bundle",permalink:"/docs/4.3/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},p,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)"))))}g.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"version-4.3/docs",previous:{title:"GraphQLite",permalink:"/docs/4.3/"},next:{title:"Symfony bundle",permalink:"/docs/4.3/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},p,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)"))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/0db959c8.cd0b2ed7.js b/assets/js/0db959c8.19be7258.js similarity index 99% rename from assets/js/0db959c8.cd0b2ed7.js rename to assets/js/0db959c8.19be7258.js index c3a5cb5ce..26c102ada 100644 --- a/assets/js/0db959c8.cd0b2ed7.js +++ b/assets/js/0db959c8.19be7258.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 y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!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,y]=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}),h=(()=>{const e=s??p;return g({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{h&&l(h)}),[h]);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),y(e)}),[u,y,o]),tabValues:o}}var h=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=y(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,h.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!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,y]=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}),h=(()=>{const e=s??p;return g({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{h&&l(h)}),[h]);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),y(e)}),[u,y,o]),tabValues:o}}var h=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=y(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,h.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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.c73ffdf3.js b/assets/js/0df2ba32.4d5523d8.js similarity index 98% rename from assets/js/0df2ba32.c73ffdf3.js rename to assets/js/0df2ba32.4d5523d8.js index 3e9772eb5..76942c842 100644 --- a/assets/js/0df2ba32.c73ffdf3.js +++ b/assets/js/0df2ba32.4d5523d8.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.9bb42ee8.js b/assets/js/0e5befdb.adfcf147.js similarity index 99% rename from assets/js/0e5befdb.9bb42ee8.js rename to assets/js/0e5befdb.adfcf147.js index a6064af48..d4ae6c4b6 100644 --- a/assets/js/0e5befdb.9bb42ee8.js +++ b/assets/js/0e5befdb.adfcf147.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.3a8223fb.js b/assets/js/0ef60658.3a0dda98.js similarity index 99% rename from assets/js/0ef60658.3a8223fb.js rename to assets/js/0ef60658.3a0dda98.js index 068fa581b..09b732a19 100644 --- a/assets/js/0ef60658.3a8223fb.js +++ b/assets/js/0ef60658.3a0dda98.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.cef60eb6.js b/assets/js/0fd21208.c7e0a6a1.js similarity index 96% rename from assets/js/0fd21208.cef60eb6.js rename to assets/js/0fd21208.c7e0a6a1.js index faf8df3f9..485abce4e 100644 --- a/assets/js/0fd21208.cef60eb6.js +++ b/assets/js/0fd21208.c7e0a6a1.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.cac6183f.js b/assets/js/102de343.ac9aff92.js similarity index 99% rename from assets/js/102de343.cac6183f.js rename to assets/js/102de343.ac9aff92.js index e54902188..3e129c69c 100644 --- a/assets/js/102de343.cac6183f.js +++ b/assets/js/102de343.ac9aff92.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.67eb69dc.js b/assets/js/107b7a36.ef8bab33.js similarity index 98% rename from assets/js/107b7a36.67eb69dc.js rename to assets/js/107b7a36.ef8bab33.js index b5d1a7cb1..1a0730876 100644 --- a/assets/js/107b7a36.67eb69dc.js +++ b/assets/js/107b7a36.ef8bab33.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.617e845b.js b/assets/js/107d11ee.6b209a8d.js similarity index 98% rename from assets/js/107d11ee.617e845b.js rename to assets/js/107d11ee.6b209a8d.js index 80532aff6..cade8dc6a 100644 --- a/assets/js/107d11ee.617e845b.js +++ b/assets/js/107d11ee.6b209a8d.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.2316a90f.js b/assets/js/12d3ef9e.e1898768.js similarity index 99% rename from assets/js/12d3ef9e.2316a90f.js rename to assets/js/12d3ef9e.e1898768.js index 19c7bf556..30e3c14fe 100644 --- a/assets/js/12d3ef9e.2316a90f.js +++ b/assets/js/12d3ef9e.e1898768.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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.ee344fe1.js b/assets/js/136c1ee9.1431f6c1.js similarity index 99% rename from assets/js/136c1ee9.ee344fe1.js rename to assets/js/136c1ee9.1431f6c1.js index a9aaf1a10..474143a1c 100644 --- a/assets/js/136c1ee9.ee344fe1.js +++ b/assets/js/136c1ee9.1431f6c1.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.f687627c.js b/assets/js/13b4aeb1.40ffa096.js similarity index 98% rename from assets/js/13b4aeb1.f687627c.js rename to assets/js/13b4aeb1.40ffa096.js index ac27128c9..2661fbe38 100644 --- a/assets/js/13b4aeb1.f687627c.js +++ b/assets/js/13b4aeb1.40ffa096.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.6eaa2756.js b/assets/js/1428bdad.2f645659.js similarity index 99% rename from assets/js/1428bdad.6eaa2756.js rename to assets/js/1428bdad.2f645659.js index f73785f5f..3207ff9df 100644 --- a/assets/js/1428bdad.6eaa2756.js +++ b/assets/js/1428bdad.2f645659.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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-system/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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-system/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.f3942f77.js b/assets/js/143f7888.1d5adaec.js similarity index 99% rename from assets/js/143f7888.f3942f77.js rename to assets/js/143f7888.1d5adaec.js index 57abc8e55..035e18f41 100644 --- a/assets/js/143f7888.f3942f77.js +++ b/assets/js/143f7888.1d5adaec.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.33beb644.js b/assets/js/15a79915.be719ff6.js similarity index 99% rename from assets/js/15a79915.33beb644.js rename to assets/js/15a79915.be719ff6.js index 4dc8be8a0..1666237fc 100644 --- a/assets/js/15a79915.33beb644.js +++ b/assets/js/15a79915.be719ff6.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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.2688abf0.js b/assets/js/15b5a907.3d50e40d.js similarity index 99% rename from assets/js/15b5a907.2688abf0.js rename to assets/js/15b5a907.3d50e40d.js index 8ce1494a7..e54163abb 100644 --- a/assets/js/15b5a907.2688abf0.js +++ b/assets/js/15b5a907.3d50e40d.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:()=>d,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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 d(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"),"."))}d.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:()=>d,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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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 d(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"),"."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/16017aa6.3eccad0d.js b/assets/js/16017aa6.a22be57e.js similarity index 99% rename from assets/js/16017aa6.3eccad0d.js rename to assets/js/16017aa6.a22be57e.js index a440b504e..8e612c47c 100644 --- a/assets/js/16017aa6.3eccad0d.js +++ b/assets/js/16017aa6.a22be57e.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.94dbe306.js b/assets/js/16565e6a.085e15ac.js similarity index 99% rename from assets/js/16565e6a.94dbe306.js rename to assets/js/16565e6a.085e15ac.js index 298fc4410..04c4b0188 100644 --- a/assets/js/16565e6a.94dbe306.js +++ b/assets/js/16565e6a.085e15ac.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.37f744be.js b/assets/js/17518879.ea89b826.js similarity index 99% rename from assets/js/17518879.37f744be.js rename to assets/js/17518879.ea89b826.js index c8a4baabf..713aba7ac 100644 --- a/assets/js/17518879.37f744be.js +++ b/assets/js/17518879.ea89b826.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.007c3177.js b/assets/js/17cca601.e8423ab3.js similarity index 99% rename from assets/js/17cca601.007c3177.js rename to assets/js/17cca601.e8423ab3.js index 08913a72e..94046e639 100644 --- a/assets/js/17cca601.007c3177.js +++ b/assets/js/17cca601.e8423ab3.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/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/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-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/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!")))}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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/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/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-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/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!")))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/18100524.fb2d6eb2.js b/assets/js/18100524.2a11f212.js similarity index 99% rename from assets/js/18100524.fb2d6eb2.js rename to assets/js/18100524.2a11f212.js index 17f74d01a..024a4469b 100644 --- a/assets/js/18100524.fb2d6eb2.js +++ b/assets/js/18100524.2a11f212.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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-system/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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-system/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.bc507d40.js b/assets/js/1891fd2b.175c467d.js similarity index 99% rename from assets/js/1891fd2b.bc507d40.js rename to assets/js/1891fd2b.175c467d.js index f2a6e5b21..9e753607a 100644 --- a/assets/js/1891fd2b.bc507d40.js +++ b/assets/js/1891fd2b.175c467d.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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-system/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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-system/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.9b1b6d63.js b/assets/js/18d6c9c9.b0c01362.js similarity index 99% rename from assets/js/18d6c9c9.9b1b6d63.js rename to assets/js/18d6c9c9.b0c01362.js index 01242eee5..b5afaf8b7 100644 --- a/assets/js/18d6c9c9.9b1b6d63.js +++ b/assets/js/18d6c9c9.b0c01362.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.a3079b3b.js b/assets/js/1aa05129.c0cd2084.js similarity index 98% rename from assets/js/1aa05129.a3079b3b.js rename to assets/js/1aa05129.c0cd2084.js index 8d8f2e9ae..d0c2cd713 100644 --- a/assets/js/1aa05129.a3079b3b.js +++ b/assets/js/1aa05129.c0cd2084.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.c56b680a.js b/assets/js/1af245cd.d7e67aae.js similarity index 99% rename from assets/js/1af245cd.c56b680a.js rename to assets/js/1af245cd.d7e67aae.js index 73abe254d..d9c56fe56 100644 --- a/assets/js/1af245cd.c56b680a.js +++ b/assets/js/1af245cd.d7e67aae.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 g(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function h(t){let{queryString:e=!1,groupId:n}=t;const a=(0,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(!g({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]=h({queryString:n,groupId:a}),[p,b]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Dv)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),m=(()=>{const t=l??p;return g({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{m&&s(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!g({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))},g=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:g,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:()=>h,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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"docs",previous:{title:"Migrating",permalink:"/docs/migrating"},next:{title:"Annotations reference",permalink:"/docs/annotations-reference"}},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},g="wrapper";function h(t){let{components:e,...n}=t;return(0,r.yg)(g,(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/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")))}h.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 g(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function h(t){let{queryString:e=!1,groupId:n}=t;const a=(0,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(!g({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]=h({queryString:n,groupId:a}),[p,b]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Dv)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),m=(()=>{const t=l??p;return g({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{m&&s(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!g({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))},g=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:g,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:()=>h,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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"},sidebar:"docs",previous:{title:"Migrating",permalink:"/docs/migrating"},next:{title:"Annotations reference",permalink:"/docs/annotations-reference"}},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},g="wrapper";function h(t){let{components:e,...n}=t;return(0,r.yg)(g,(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/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")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1b1927f4.569471ed.js b/assets/js/1b1927f4.a9a56397.js similarity index 98% rename from assets/js/1b1927f4.569471ed.js rename to assets/js/1b1927f4.a9a56397.js index 112104790..d9aaf79a9 100644 --- a/assets/js/1b1927f4.569471ed.js +++ b/assets/js/1b1927f4.a9a56397.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.15824987.js b/assets/js/1ba75d10.d2fc3080.js similarity index 99% rename from assets/js/1ba75d10.15824987.js rename to assets/js/1ba75d10.d2fc3080.js index 8be1e6784..801cbdf0a 100644 --- a/assets/js/1ba75d10.15824987.js +++ b/assets/js/1ba75d10.d2fc3080.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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.b2e2ea24.js b/assets/js/1ca907c0.880728de.js similarity index 98% rename from assets/js/1ca907c0.b2e2ea24.js rename to assets/js/1ca907c0.880728de.js index 8af5ecde6..a13df9d7b 100644 --- a/assets/js/1ca907c0.b2e2ea24.js +++ b/assets/js/1ca907c0.880728de.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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={},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/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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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={},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/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.86bf69c5.js b/assets/js/1d20a4b3.7b84c748.js similarity index 99% rename from assets/js/1d20a4b3.86bf69c5.js rename to assets/js/1d20a4b3.7b84c748.js index 9c988a068..4f77b41a7 100644 --- a/assets/js/1d20a4b3.86bf69c5.js +++ b/assets/js/1d20a4b3.7b84c748.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2596],{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),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)(),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 h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,l=g(e),[o,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:l}))),[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,l]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(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}`);i(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:i,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!==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,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:i===a?0:-1,"aria-selected":i===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":i===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))}},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)),l=(t(67443),t(11470)),o=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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/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)("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/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/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:()=>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),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)(),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 h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,l=g(e),[o,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:l}))),[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,l]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(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}`);i(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:i,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!==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,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:i===a?0:-1,"aria-selected":i===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":i===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))}},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)),l=(t(67443),t(11470)),o=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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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/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)("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/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/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.c3571e4c.js b/assets/js/1d703573.6488b685.js similarity index 97% rename from assets/js/1d703573.c3571e4c.js rename to assets/js/1d703573.6488b685.js index a8e2cbdb6..b9f9b010f 100644 --- a/assets/js/1d703573.c3571e4c.js +++ b/assets/js/1d703573.6488b685.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"version-4.2/docs",previous:{title:"GraphQLite",permalink:"/docs/4.2/"},next:{title:"Symfony bundle",permalink:"/docs/4.2/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},p,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)"))))}g.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"version-4.2/docs",previous:{title:"GraphQLite",permalink:"/docs/4.2/"},next:{title:"Symfony bundle",permalink:"/docs/4.2/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},p,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)"))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/1e2c5f46.b48d6e58.js b/assets/js/1e2c5f46.def37f02.js similarity index 98% rename from assets/js/1e2c5f46.b48d6e58.js rename to assets/js/1e2c5f46.def37f02.js index 49b1fc33e..465211dc0 100644 --- a/assets/js/1e2c5f46.b48d6e58.js +++ b/assets/js/1e2c5f46.def37f02.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.a9f97779.js b/assets/js/1e6ec01e.79a26d94.js similarity index 99% rename from assets/js/1e6ec01e.a9f97779.js rename to assets/js/1e6ec01e.79a26d94.js index 30d9fcb5c..737f15a87 100644 --- a/assets/js/1e6ec01e.a9f97779.js +++ b/assets/js/1e6ec01e.79a26d94.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.10e1b4b0.js b/assets/js/1e7fe27e.d543f284.js similarity index 99% rename from assets/js/1e7fe27e.10e1b4b0.js rename to assets/js/1e7fe27e.d543f284.js index 8bb40c25d..b8d4cc52d 100644 --- a/assets/js/1e7fe27e.10e1b4b0.js +++ b/assets/js/1e7fe27e.d543f284.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.8e8b73ef.js b/assets/js/1ea13486.621658df.js similarity index 98% rename from assets/js/1ea13486.8e8b73ef.js rename to assets/js/1ea13486.621658df.js index 563304ecb..fc7fad200 100644 --- a/assets/js/1ea13486.8e8b73ef.js +++ b/assets/js/1ea13486.621658df.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.9b4e4601.js b/assets/js/1edb88e5.c186a972.js similarity index 99% rename from assets/js/1edb88e5.9b4e4601.js rename to assets/js/1edb88e5.c186a972.js index ff9e76487..586f8e33c 100644 --- a/assets/js/1edb88e5.9b4e4601.js +++ b/assets/js/1edb88e5.c186a972.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.b23e918f.js b/assets/js/1f5af0f2.1e16655c.js similarity index 98% rename from assets/js/1f5af0f2.b23e918f.js rename to assets/js/1f5af0f2.1e16655c.js index 40dd15f60..e682c65f3 100644 --- a/assets/js/1f5af0f2.b23e918f.js +++ b/assets/js/1f5af0f2.1e16655c.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.bd784f60.js b/assets/js/1f5e9707.cb48452a.js similarity index 99% rename from assets/js/1f5e9707.bd784f60.js rename to assets/js/1f5e9707.cb48452a.js index 3a3113e1a..e1f1ef7bf 100644 --- a/assets/js/1f5e9707.bd784f60.js +++ b/assets/js/1f5e9707.cb48452a.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.9a25270f.js b/assets/js/2014e4e3.f5c34a4b.js similarity index 98% rename from assets/js/2014e4e3.9a25270f.js rename to assets/js/2014e4e3.f5c34a4b.js index 4c99db821..57fc710a8 100644 --- a/assets/js/2014e4e3.9a25270f.js +++ b/assets/js/2014e4e3.f5c34a4b.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.bc6f4eb1.js b/assets/js/20540af3.7b8b47f6.js similarity index 99% rename from assets/js/20540af3.bc6f4eb1.js rename to assets/js/20540af3.7b8b47f6.js index 153af1a57..7043a671e 100644 --- a/assets/js/20540af3.bc6f4eb1.js +++ b/assets/js/20540af3.7b8b47f6.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/semver"}},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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"annotations-reference",title:"Annotations reference",sidebar_label:"Annotations reference"},sidebar:"docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/semver"}},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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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.cfa95698.js b/assets/js/21637dff.bc0d8785.js similarity index 99% rename from assets/js/21637dff.cfa95698.js rename to assets/js/21637dff.bc0d8785.js index cf1b5bd6d..2ede4a287 100644 --- a/assets/js/21637dff.cfa95698.js +++ b/assets/js/21637dff.bc0d8785.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 p(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 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,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=p(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}))),[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 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),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_)(),p=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},h=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 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:h,onClick:p},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"version-4.2/docs",previous:{title:"User input validation",permalink:"/docs/4.2/validation"},next:{title:"Fine grained security",permalink:"/docs/4.2/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(h,(0,a.A)({},p,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 p(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 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,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=p(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}))),[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 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),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_)(),p=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},h=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 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:h,onClick:p},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"version-4.2/docs",previous:{title:"User input validation",permalink:"/docs/4.2/validation"},next:{title:"Fine grained security",permalink:"/docs/4.2/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(h,(0,a.A)({},p,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.e2584029.js b/assets/js/21a7a3b0.98695aa2.js similarity index 99% rename from assets/js/21a7a3b0.e2584029.js rename to assets/js/21a7a3b0.98695aa2.js index 10055eae9..51ec7045d 100644 --- a/assets/js/21a7a3b0.e2584029.js +++ b/assets/js/21a7a3b0.98695aa2.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.2dda92b3.js b/assets/js/21cde469.42de3ab5.js similarity index 99% rename from assets/js/21cde469.2dda92b3.js rename to assets/js/21cde469.42de3ab5.js index 177a3d170..4e2d4b0e6 100644 --- a/assets/js/21cde469.2dda92b3.js +++ b/assets/js/21cde469.42de3ab5.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),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 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:()=>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-4.2/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-4.2/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/4.2/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/error-handling.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"version-4.2/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/4.2/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/4.2/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function 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),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 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:()=>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-4.2/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-4.2/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/4.2/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/error-handling.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"version-4.2/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/4.2/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/4.2/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function 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.46a87359.js b/assets/js/22e1e32f.a63c9c7d.js similarity index 99% rename from assets/js/22e1e32f.46a87359.js rename to assets/js/22e1e32f.a63c9c7d.js index 65d1c6d39..92e09a905 100644 --- a/assets/js/22e1e32f.46a87359.js +++ b/assets/js/22e1e32f.a63c9c7d.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.6102f5c2.js b/assets/js/232afa3a.4989b07d.js similarity index 98% rename from assets/js/232afa3a.6102f5c2.js rename to assets/js/232afa3a.4989b07d.js index 0ba2381f8..3e3e811f0 100644 --- a/assets/js/232afa3a.6102f5c2.js +++ b/assets/js/232afa3a.4989b07d.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 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))}},41002:(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"},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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},p={},d=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:3},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:3},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:3},{value:"Usage",id:"usage",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.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)("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 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))}},41002:(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"},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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},p={},d=[{value:"Installation",id:"installation",level:2},{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:3},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:3},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:3},{value:"Usage",id:"usage",level:2}],c={toc:d},m="wrapper";function h(e){let{components:t,...a}=e;return(0,r.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)("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.ec196a8f.js b/assets/js/2355609d.3ad1d9e5.js similarity index 98% rename from assets/js/2355609d.ec196a8f.js rename to assets/js/2355609d.3ad1d9e5.js index 56226600a..8bff79e4e 100644 --- a/assets/js/2355609d.ec196a8f.js +++ b/assets/js/2355609d.3ad1d9e5.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.be36c6f0.js b/assets/js/23794275.2d3cafaf.js similarity index 99% rename from assets/js/23794275.be36c6f0.js rename to assets/js/23794275.2d3cafaf.js index 397e6093f..2f25b8e44 100644 --- a/assets/js/23794275.be36c6f0.js +++ b/assets/js/23794275.2d3cafaf.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.6f8e7fa6.js b/assets/js/23a8ac29.fef39a38.js similarity index 99% rename from assets/js/23a8ac29.6f8e7fa6.js rename to assets/js/23a8ac29.fef39a38.js index 54fe81776..1b1184002 100644 --- a/assets/js/23a8ac29.6f8e7fa6.js +++ b/assets/js/23a8ac29.fef39a38.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.eb057b4d.js b/assets/js/23f642f2.702af88f.js similarity index 99% rename from assets/js/23f642f2.eb057b4d.js rename to assets/js/23f642f2.702af88f.js index 0f6d60630..c64708af9 100644 --- a/assets/js/23f642f2.eb057b4d.js +++ b/assets/js/23f642f2.702af88f.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 g(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,g]=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}),m=(()=>{const e=i??c;return y({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{m&&u(m)}),[m]);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),g(e)}),[p,g,o]),tabValues:o}}var m=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=g(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,m.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 g(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,g]=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}),m=(()=>{const e=i??c;return y({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{m&&u(m)}),[m]);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),g(e)}),[p,g,o]),tabValues:o}}var m=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=g(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,m.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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ff085183.js b/assets/js/242d99d9.65e7903b.js similarity index 97% rename from assets/js/242d99d9.ff085183.js rename to assets/js/242d99d9.65e7903b.js index 313d8366c..4c1bfa16b 100644 --- a/assets/js/242d99d9.ff085183.js +++ b/assets/js/242d99d9.65e7903b.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:()=>c,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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},p="wrapper";function c(e){let{components:t,...o}=e;return(0,r.yg)(p,(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."))}c.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:()=>c,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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},p="wrapper";function c(e){let{components:t,...o}=e;return(0,r.yg)(p,(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."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/24ac61c7.0594428c.js b/assets/js/24ac61c7.56754f4a.js similarity index 96% rename from assets/js/24ac61c7.0594428c.js rename to assets/js/24ac61c7.56754f4a.js index b3a7d59b1..89b1f0b6d 100644 --- a/assets/js/24ac61c7.0594428c.js +++ b/assets/js/24ac61c7.56754f4a.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.7f44594c.js b/assets/js/24aca886.067e7bc9.js similarity index 99% rename from assets/js/24aca886.7f44594c.js rename to assets/js/24aca886.067e7bc9.js index d54a3fd2f..5b8e86c4c 100644 --- a/assets/js/24aca886.7f44594c.js +++ b/assets/js/24aca886.067e7bc9.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.57911023.js b/assets/js/25d4129e.0452c424.js similarity index 99% rename from assets/js/25d4129e.57911023.js rename to assets/js/25d4129e.0452c424.js index 1fc6ea305..2226178b3 100644 --- a/assets/js/25d4129e.57911023.js +++ b/assets/js/25d4129e.0452c424.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),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 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:()=>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-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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/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),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 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:()=>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-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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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/symfony-bundle"},"Symfony"),", ",(0,a.yg)("a",{parentName:"p",href:"/docs/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.fd45594c.js b/assets/js/263ebc7a.ab66a253.js similarity index 99% rename from assets/js/263ebc7a.fd45594c.js rename to assets/js/263ebc7a.ab66a253.js index 5a6480e89..f1e8f94b0 100644 --- a/assets/js/263ebc7a.fd45594c.js +++ b/assets/js/263ebc7a.ab66a253.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.c3e74a31.js b/assets/js/26662da3.fe57afd5.js similarity index 99% rename from assets/js/26662da3.c3e74a31.js rename to assets/js/26662da3.fe57afd5.js index b1b279a53..b7248e905 100644 --- a/assets/js/26662da3.c3e74a31.js +++ b/assets/js/26662da3.fe57afd5.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ecb27e90.js b/assets/js/26a27afb.f2ee3b29.js similarity index 99% rename from assets/js/26a27afb.ecb27e90.js rename to assets/js/26a27afb.f2ee3b29.js index 083df917a..9e9cb75f2 100644 --- a/assets/js/26a27afb.ecb27e90.js +++ b/assets/js/26a27afb.f2ee3b29.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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-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"),". 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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-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"),". 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.20ddf17d.js b/assets/js/27b414e3.a918f7e4.js similarity index 99% rename from assets/js/27b414e3.20ddf17d.js rename to assets/js/27b414e3.a918f7e4.js index f0e7e6569..3177c4720 100644 --- a/assets/js/27b414e3.20ddf17d.js +++ b/assets/js/27b414e3.a918f7e4.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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/28c12eaf.f79d3873.js b/assets/js/28c12eaf.0bf95a09.js similarity index 99% rename from assets/js/28c12eaf.f79d3873.js rename to assets/js/28c12eaf.0bf95a09.js index 6a1064cc1..988814b85 100644 --- a/assets/js/28c12eaf.f79d3873.js +++ b/assets/js/28c12eaf.0bf95a09.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.4ec91853.js b/assets/js/2917b31e.f9c0b568.js similarity index 99% rename from assets/js/2917b31e.4ec91853.js rename to assets/js/2917b31e.f9c0b568.js index 48bce6b90..71be4f572 100644 --- a/assets/js/2917b31e.4ec91853.js +++ b/assets/js/2917b31e.f9c0b568.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/pagination"},next:{title:"Custom annotations",permalink:"/docs/field-middlewares"}},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-system/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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"custom-types",title:"Custom types",sidebar_label:"Custom types"},sidebar:"docs",previous:{title:"Pagination",permalink:"/docs/pagination"},next:{title:"Custom annotations",permalink:"/docs/field-middlewares"}},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-system/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.be7c1a69.js b/assets/js/29a6c1ba.771a3fc1.js similarity index 99% rename from assets/js/29a6c1ba.be7c1a69.js rename to assets/js/29a6c1ba.771a3fc1.js index f560a9e80..0de0c92f6 100644 --- a/assets/js/29a6c1ba.be7c1a69.js +++ b/assets/js/29a6c1ba.771a3fc1.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 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))}},28376:(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"},o=void 0,p={unversionedId:"multiple-output-types",id:"version-4.2/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.2/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/4.2/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/multiple-output-types.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"version-4.2/docs",previous:{title:"Extending an input type",permalink:"/docs/4.2/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/4.2/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},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.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 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))}},28376:(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"},o=void 0,p={unversionedId:"multiple-output-types",id:"version-4.2/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.2/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/4.2/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/multiple-output-types.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"version-4.2/docs",previous:{title:"Extending an input type",permalink:"/docs/4.2/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/4.2/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},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.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.e5209db4.js b/assets/js/29cf2ad6.f26d1860.js similarity index 99% rename from assets/js/29cf2ad6.e5209db4.js rename to assets/js/29cf2ad6.f26d1860.js index 0f1998ab7..ece8d2a3e 100644 --- a/assets/js/29cf2ad6.e5209db4.js +++ b/assets/js/29cf2ad6.f26d1860.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.a2d49345.js b/assets/js/2b26025e.2350cefd.js similarity index 97% rename from assets/js/2b26025e.a2d49345.js rename to assets/js/2b26025e.2350cefd.js index 826853131..48bda3d27 100644 --- a/assets/js/2b26025e.a2d49345.js +++ b/assets/js/2b26025e.2350cefd.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.b4e123c4.js b/assets/js/2bbfc5d5.545fc5e5.js similarity index 99% rename from assets/js/2bbfc5d5.b4e123c4.js rename to assets/js/2bbfc5d5.545fc5e5.js index a2db7dccd..b77f96cf0 100644 --- a/assets/js/2bbfc5d5.b4e123c4.js +++ b/assets/js/2bbfc5d5.545fc5e5.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),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))}},35529:(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-3.0/multiple_output_types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-3.0/multiple_output_types.mdx",sourceDirName:".",slug:"/multiple_output_types",permalink:"/docs/3.0/multiple_output_types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/multiple_output_types.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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),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))}},35529:(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-3.0/multiple_output_types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-3.0/multiple_output_types.mdx",sourceDirName:".",slug:"/multiple_output_types",permalink:"/docs/3.0/multiple_output_types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/multiple_output_types.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.df37da76.js b/assets/js/2d02c83c.42480db1.js similarity index 98% rename from assets/js/2d02c83c.df37da76.js rename to assets/js/2d02c83c.42480db1.js index a946734da..ad23a83b8 100644 --- a/assets/js/2d02c83c.df37da76.js +++ b/assets/js/2d02c83c.42480db1.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.87e9f636.js b/assets/js/2d4548df.5485b326.js similarity index 99% rename from assets/js/2d4548df.87e9f636.js rename to assets/js/2d4548df.5485b326.js index b93323f0f..7d7909973 100644 --- a/assets/js/2d4548df.87e9f636.js +++ b/assets/js/2d4548df.5485b326.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ea5ae136.js b/assets/js/2e25c87f.05446db0.js similarity index 99% rename from assets/js/2e25c87f.ea5ae136.js rename to assets/js/2e25c87f.05446db0.js index 39885725b..1e72869f4 100644 --- a/assets/js/2e25c87f.ea5ae136.js +++ b/assets/js/2e25c87f.05446db0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1345],{8608:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>i,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>s});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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"docs",previous:{title:"Getting Started",permalink:"/docs/next/getting-started"},next:{title:"Laravel package",permalink:"/docs/next/laravel-package"}},p={},s=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],c={toc:s},d="wrapper";function g(e){let{components:n,...t}=e;return(0,l.yg)(d,(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:()=>p,contentTitle:()=>i,default:()=>g,frontMatter:()=>r,metadata:()=>o,toc:()=>s});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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"symfony-bundle",title:"Getting started with Symfony",sidebar_label:"Symfony bundle"},sidebar:"docs",previous:{title:"Getting Started",permalink:"/docs/next/getting-started"},next:{title:"Laravel package",permalink:"/docs/next/laravel-package"}},p={},s=[{value:"Applications that use Symfony Flex",id:"applications-that-use-symfony-flex",level:2},{value:"Applications that don't use Symfony Flex",id:"applications-that-dont-use-symfony-flex",level:2},{value:"Advanced configuration",id:"advanced-configuration",level:2},{value:"Customizing error handling",id:"customizing-error-handling",level:3}],c={toc:s},d="wrapper";function g(e){let{components:n,...t}=e;return(0,l.yg)(d,(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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.a4397b07.js b/assets/js/2ef99682.5ea187f2.js similarity index 99% rename from assets/js/2ef99682.a4397b07.js rename to assets/js/2ef99682.5ea187f2.js index f313c3ab6..51024a7c1 100644 --- a/assets/js/2ef99682.a4397b07.js +++ b/assets/js/2ef99682.5ea187f2.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.6f491d09.js b/assets/js/2f36012a.16b48290.js similarity index 98% rename from assets/js/2f36012a.6f491d09.js rename to assets/js/2f36012a.16b48290.js index c99194eb0..5838473ef 100644 --- a/assets/js/2f36012a.6f491d09.js +++ b/assets/js/2f36012a.16b48290.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/30940d42.4f0f3c44.js b/assets/js/30940d42.e7f62cec.js similarity index 99% rename from assets/js/30940d42.4f0f3c44.js rename to assets/js/30940d42.e7f62cec.js index c85bd239f..69870f1ab 100644 --- a/assets/js/30940d42.4f0f3c44.js +++ b/assets/js/30940d42.e7f62cec.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>c,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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},p="wrapper";function c(t){let{components:e,...a}=t;return(0,i.yg)(p,(0,r.A)({},g,a,{components:e,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)"))))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6972],{24664:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>c,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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},p="wrapper";function c(t){let{components:e,...a}=t;return(0,i.yg)(p,(0,r.A)({},g,a,{components:e,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)"))))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/323a980a.6b82ac7e.js b/assets/js/323a980a.13853cf0.js similarity index 98% rename from assets/js/323a980a.6b82ac7e.js rename to assets/js/323a980a.13853cf0.js index 34706ff7a..9565626b6 100644 --- a/assets/js/323a980a.6b82ac7e.js +++ b/assets/js/323a980a.13853cf0.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/332827b4.d4c1e857.js b/assets/js/332827b4.f5ff9c8a.js similarity index 98% rename from assets/js/332827b4.d4c1e857.js rename to assets/js/332827b4.f5ff9c8a.js index ee7ce5baa..48bc26e4e 100644 --- a/assets/js/332827b4.d4c1e857.js +++ b/assets/js/332827b4.f5ff9c8a.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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([[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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/346bcb92.89b2ce95.js b/assets/js/346bcb92.16595548.js similarity index 99% rename from assets/js/346bcb92.89b2ce95.js rename to assets/js/346bcb92.16595548.js index f094442be..99fe1549e 100644 --- a/assets/js/346bcb92.89b2ce95.js +++ b/assets/js/346bcb92.16595548.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.cedd99eb.js b/assets/js/354a9b78.46c818e8.js similarity index 98% rename from assets/js/354a9b78.cedd99eb.js rename to assets/js/354a9b78.46c818e8.js index 7870cbe68..3ba66ea69 100644 --- a/assets/js/354a9b78.cedd99eb.js +++ b/assets/js/354a9b78.46c818e8.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.4f5e8a84.js b/assets/js/366cfce3.072044f3.js similarity index 99% rename from assets/js/366cfce3.4f5e8a84.js rename to assets/js/366cfce3.072044f3.js index 5e86afcb3..f2335bcad 100644 --- a/assets/js/366cfce3.4f5e8a84.js +++ b/assets/js/366cfce3.072044f3.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/36ddade1.e248315d.js b/assets/js/36ddade1.52451906.js similarity index 97% rename from assets/js/36ddade1.e248315d.js rename to assets/js/36ddade1.52451906.js index 95ce6876d..846ba2bbb 100644 --- a/assets/js/36ddade1.e248315d.js +++ b/assets/js/36ddade1.52451906.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"docs",previous:{title:"GraphQLite",permalink:"/docs/6.0/"},next:{title:"Symfony bundle",permalink:"/docs/6.0/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},p,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)"))))}g.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"docs",previous:{title:"GraphQLite",permalink:"/docs/6.0/"},next:{title:"Symfony bundle",permalink:"/docs/6.0/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},p,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)"))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/379bfe51.7edce05a.js b/assets/js/379bfe51.ae5ebb8e.js similarity index 99% rename from assets/js/379bfe51.7edce05a.js rename to assets/js/379bfe51.ae5ebb8e.js index 5156085ee..015dbfc38 100644 --- a/assets/js/379bfe51.7edce05a.js +++ b/assets/js/379bfe51.ae5ebb8e.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.cb57eedc.js b/assets/js/380575ae.0fb3b47d.js similarity index 99% rename from assets/js/380575ae.cb57eedc.js rename to assets/js/380575ae.0fb3b47d.js index 2d54d435e..63439ecb0 100644 --- a/assets/js/380575ae.cb57eedc.js +++ b/assets/js/380575ae.0fb3b47d.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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.f454350d.js b/assets/js/38317547.a1b9180d.js similarity index 96% rename from assets/js/38317547.f454350d.js rename to assets/js/38317547.a1b9180d.js index 961b2c48d..1ac47339a 100644 --- a/assets/js/38317547.f454350d.js +++ b/assets/js/38317547.a1b9180d.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.c56a066d.js b/assets/js/38cf1c7a.01e4fa32.js similarity index 99% rename from assets/js/38cf1c7a.c56a066d.js rename to assets/js/38cf1c7a.01e4fa32.js index ab1230652..70b55c4c6 100644 --- a/assets/js/38cf1c7a.c56a066d.js +++ b/assets/js/38cf1c7a.01e4fa32.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.60a413eb.js b/assets/js/394f3211.81f00e53.js similarity index 99% rename from assets/js/394f3211.60a413eb.js rename to assets/js/394f3211.81f00e53.js index c152e3d22..dbd745bc2 100644 --- a/assets/js/394f3211.60a413eb.js +++ b/assets/js/394f3211.81f00e53.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/3b486936.410100a2.js b/assets/js/3b486936.e4e39654.js similarity index 97% rename from assets/js/3b486936.410100a2.js rename to assets/js/3b486936.e4e39654.js index 781f554dc..da47c9b2b 100644 --- a/assets/js/3b486936.410100a2.js +++ b/assets/js/3b486936.e4e39654.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8100],{70177:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"version-5.0/docs",previous:{title:"Internals",permalink:"/docs/5.0/internals"},next:{title:"Migrating",permalink:"/docs/5.0/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},p,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."))}d.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"version-5.0/docs",previous:{title:"Internals",permalink:"/docs/5.0/internals"},next:{title:"Migrating",permalink:"/docs/5.0/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},p,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."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/3d0eb74d.c0a1bbde.js b/assets/js/3d0eb74d.2b99da9d.js similarity index 99% rename from assets/js/3d0eb74d.c0a1bbde.js rename to assets/js/3d0eb74d.2b99da9d.js index 6240a25e7..242022a2b 100644 --- a/assets/js/3d0eb74d.c0a1bbde.js +++ b/assets/js/3d0eb74d.2b99da9d.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.83281771.js b/assets/js/3f944aba.3c25cf0e.js similarity index 98% rename from assets/js/3f944aba.83281771.js rename to assets/js/3f944aba.3c25cf0e.js index b5e16c2a1..04b369512 100644 --- a/assets/js/3f944aba.83281771.js +++ b/assets/js/3f944aba.3c25cf0e.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.82e55cef.js b/assets/js/400ddbbb.9a45cf17.js similarity index 99% rename from assets/js/400ddbbb.82e55cef.js rename to assets/js/400ddbbb.9a45cf17.js index c97af572c..61e8dabe3 100644 --- a/assets/js/400ddbbb.82e55cef.js +++ b/assets/js/400ddbbb.9a45cf17.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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.6b3b89b3.js b/assets/js/4194805f.a49fe3a4.js similarity index 99% rename from assets/js/4194805f.6b3b89b3.js rename to assets/js/4194805f.a49fe3a4.js index 186066581..b86163f00 100644 --- a/assets/js/4194805f.6b3b89b3.js +++ b/assets/js/4194805f.a49fe3a4.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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/471c3e37.2a377d4d.js b/assets/js/471c3e37.93d9c059.js similarity index 99% rename from assets/js/471c3e37.2a377d4d.js rename to assets/js/471c3e37.93d9c059.js index ac2bd938f..1c5779caf 100644 --- a/assets/js/471c3e37.2a377d4d.js +++ b/assets/js/471c3e37.93d9c059.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.1f0fc197.js b/assets/js/48fde361.98272508.js similarity index 99% rename from assets/js/48fde361.1f0fc197.js rename to assets/js/48fde361.98272508.js index 843769b26..a0b105b19 100644 --- a/assets/js/48fde361.1f0fc197.js +++ b/assets/js/48fde361.98272508.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.83af7d17.js b/assets/js/4a060504.2f73632b.js similarity index 99% rename from assets/js/4a060504.83af7d17.js rename to assets/js/4a060504.2f73632b.js index 0e05ec93f..cf21dd010 100644 --- a/assets/js/4a060504.83af7d17.js +++ b/assets/js/4a060504.2f73632b.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ac98ae89.js b/assets/js/4a07aaf0.9163f54f.js similarity index 98% rename from assets/js/4a07aaf0.ac98ae89.js rename to assets/js/4a07aaf0.9163f54f.js index 8b76ffb0e..2aee8b304 100644 --- a/assets/js/4a07aaf0.ac98ae89.js +++ b/assets/js/4a07aaf0.9163f54f.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.4eb1119f.js b/assets/js/4a2da18c.2de5b1b3.js similarity index 98% rename from assets/js/4a2da18c.4eb1119f.js rename to assets/js/4a2da18c.2de5b1b3.js index 7dca7ac5b..36dae7ae0 100644 --- a/assets/js/4a2da18c.4eb1119f.js +++ b/assets/js/4a2da18c.2de5b1b3.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.89b3df88.js b/assets/js/4aab8b8c.7218bae3.js similarity index 99% rename from assets/js/4aab8b8c.89b3df88.js rename to assets/js/4aab8b8c.7218bae3.js index f677cfeb4..eae5f7f9f 100644 --- a/assets/js/4aab8b8c.89b3df88.js +++ b/assets/js/4aab8b8c.7218bae3.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.73a284a0.js b/assets/js/4bdafdff.0a931b29.js similarity index 99% rename from assets/js/4bdafdff.73a284a0.js rename to assets/js/4bdafdff.0a931b29.js index 0a8f9576e..a362ed649 100644 --- a/assets/js/4bdafdff.73a284a0.js +++ b/assets/js/4bdafdff.0a931b29.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.4ac6e79a.js b/assets/js/4c5bf49d.a481b861.js similarity index 99% rename from assets/js/4c5bf49d.4ac6e79a.js rename to assets/js/4c5bf49d.a481b861.js index 7f5aaca5c..bb1a816f6 100644 --- a/assets/js/4c5bf49d.4ac6e79a.js +++ b/assets/js/4c5bf49d.a481b861.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:()=>w});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 w(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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/queries"},next:{title:"Subscriptions",permalink:"/docs/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/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:()=>w});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 w(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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"mutations",title:"Mutations",sidebar_label:"Mutations"},sidebar:"docs",previous:{title:"Queries",permalink:"/docs/queries"},next:{title:"Subscriptions",permalink:"/docs/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/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.c8dd7aab.js b/assets/js/4c7f7507.02676f01.js similarity index 99% rename from assets/js/4c7f7507.c8dd7aab.js rename to assets/js/4c7f7507.02676f01.js index 89a02714d..2a5bb4c72 100644 --- a/assets/js/4c7f7507.c8dd7aab.js +++ b/assets/js/4c7f7507.02676f01.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.9dff7708.js b/assets/js/4d00e03a.91ddc8d5.js similarity index 99% rename from assets/js/4d00e03a.9dff7708.js rename to assets/js/4d00e03a.91ddc8d5.js index fc5083f60..5319d1434 100644 --- a/assets/js/4d00e03a.9dff7708.js +++ b/assets/js/4d00e03a.91ddc8d5.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.bd40789e.js b/assets/js/4d049718.73044c16.js similarity index 99% rename from assets/js/4d049718.bd40789e.js rename to assets/js/4d049718.73044c16.js index cc3d5bb6b..c312413d2 100644 --- a/assets/js/4d049718.bd40789e.js +++ b/assets/js/4d049718.73044c16.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ea6539f6.js b/assets/js/4d68b066.83f4dcfb.js similarity index 98% rename from assets/js/4d68b066.ea6539f6.js rename to assets/js/4d68b066.83f4dcfb.js index 76c220170..29632f5ba 100644 --- a/assets/js/4d68b066.ea6539f6.js +++ b/assets/js/4d68b066.83f4dcfb.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:()=>u,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning",original_id:"semver"},sidebar:"version-4.1/docs",previous:{title:"Annotations reference",permalink:"/docs/4.1/annotations_reference"},next:{title:"Changelog",permalink:"/docs/4.1/changelog"}},l={},p=[],m={toc:p},d="wrapper";function u(e){let{components:a,...t}=e;return(0,n.yg)(d,(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."))}u.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:()=>u,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning",original_id:"semver"},sidebar:"version-4.1/docs",previous:{title:"Annotations reference",permalink:"/docs/4.1/annotations_reference"},next:{title:"Changelog",permalink:"/docs/4.1/changelog"}},l={},p=[],m={toc:p},d="wrapper";function u(e){let{components:a,...t}=e;return(0,n.yg)(d,(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."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/4dd5816e.1347aa25.js b/assets/js/4dd5816e.ea996778.js similarity index 99% rename from assets/js/4dd5816e.1347aa25.js rename to assets/js/4dd5816e.ea996778.js index cc746faad..ab56b1bf0 100644 --- a/assets/js/4dd5816e.1347aa25.js +++ b/assets/js/4dd5816e.ea996778.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1604],{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),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)(),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 h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,l=g(e),[o,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:l}))),[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,l]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(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}`);i(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:i,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!==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,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:i===a?0:-1,"aria-selected":i===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":i===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))}},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)),l=(t(67443),t(11470)),o=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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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)(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)("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/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)(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/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:()=>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),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)(),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 h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,l=g(e),[o,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:l}))),[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,l]=(0,p.Dv)(t);return[n,(0,r.useCallback)((e=>{t&&l.set(e)}),[t,l])]}({groupId:n}),m=(()=>{const e=s??c;return d({value:e,tabValues:l})?e:null})();(0,r.useLayoutEffect)((()=>{m&&i(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}`);i(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:i,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!==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,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:i===a?0:-1,"aria-selected":i===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":i===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))}},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)),l=(t(67443),t(11470)),o=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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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)(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)("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/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)(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/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.faf621ba.js b/assets/js/4dfeb783.f77b3a45.js similarity index 99% rename from assets/js/4dfeb783.faf621ba.js rename to assets/js/4dfeb783.f77b3a45.js index 00913e5d3..f034a3cdc 100644 --- a/assets/js/4dfeb783.faf621ba.js +++ b/assets/js/4dfeb783.f77b3a45.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 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))}},10149:(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"},o=void 0,p={unversionedId:"multiple-output-types",id:"version-4.3/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.3/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/4.3/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/multiple-output-types.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"version-4.3/docs",previous:{title:"Extending an input type",permalink:"/docs/4.3/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/4.3/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},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.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 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))}},10149:(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"},o=void 0,p={unversionedId:"multiple-output-types",id:"version-4.3/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.3/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/4.3/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/multiple-output-types.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"version-4.3/docs",previous:{title:"Extending an input type",permalink:"/docs/4.3/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/4.3/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},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.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.3f9b7190.js b/assets/js/4e1a0951.d5de8cab.js similarity index 99% rename from assets/js/4e1a0951.3f9b7190.js rename to assets/js/4e1a0951.d5de8cab.js index 3e1d761d6..506655b8c 100644 --- a/assets/js/4e1a0951.3f9b7190.js +++ b/assets/js/4e1a0951.d5de8cab.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.3b18a39d.js b/assets/js/4e73bd72.8da00f07.js similarity index 96% rename from assets/js/4e73bd72.3b18a39d.js rename to assets/js/4e73bd72.8da00f07.js index 78612c50b..8fa0a5c12 100644 --- a/assets/js/4e73bd72.3b18a39d.js +++ b/assets/js/4e73bd72.8da00f07.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/4f30448a.cc668b1d.js b/assets/js/4f30448a.e44fb11b.js similarity index 99% rename from assets/js/4f30448a.cc668b1d.js rename to assets/js/4f30448a.e44fb11b.js index c47e8c5a4..505d2769b 100644 --- a/assets/js/4f30448a.cc668b1d.js +++ b/assets/js/4f30448a.e44fb11b.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.f4ad5c07.js b/assets/js/4f4b6633.4ebd402a.js similarity index 99% rename from assets/js/4f4b6633.f4ad5c07.js rename to assets/js/4f4b6633.4ebd402a.js index 226286b6f..6cbd79efe 100644 --- a/assets/js/4f4b6633.f4ad5c07.js +++ b/assets/js/4f4b6633.4ebd402a.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 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))}},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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}],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/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 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))}},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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}],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/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.a1b41e48.js b/assets/js/4f59166d.41f72369.js similarity index 99% rename from assets/js/4f59166d.a1b41e48.js rename to assets/js/4f59166d.41f72369.js index 430a4df85..ef81f922b 100644 --- a/assets/js/4f59166d.a1b41e48.js +++ b/assets/js/4f59166d.41f72369.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.634f36b4.js b/assets/js/4f6c3156.4814e7e0.js similarity index 99% rename from assets/js/4f6c3156.634f36b4.js rename to assets/js/4f6c3156.4814e7e0.js index e88f047e7..5feffcb23 100644 --- a/assets/js/4f6c3156.634f36b4.js +++ b/assets/js/4f6c3156.4814e7e0.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.e7054e4a.js b/assets/js/50122f86.0f469e64.js similarity index 98% rename from assets/js/50122f86.e7054e4a.js rename to assets/js/50122f86.0f469e64.js index 7d861dd58..8059c305b 100644 --- a/assets/js/50122f86.e7054e4a.js +++ b/assets/js/50122f86.0f469e64.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.cfc4398d.js b/assets/js/504e6c2d.47ec9159.js similarity index 99% rename from assets/js/504e6c2d.cfc4398d.js rename to assets/js/504e6c2d.47ec9159.js index 7502bc63b..41a4a45e9 100644 --- a/assets/js/504e6c2d.cfc4398d.js +++ b/assets/js/504e6c2d.47ec9159.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.714400f3.js b/assets/js/509d2004.1a6cb1b3.js similarity index 99% rename from assets/js/509d2004.714400f3.js rename to assets/js/509d2004.1a6cb1b3.js index 9cc3c820b..f39a3abef 100644 --- a/assets/js/509d2004.714400f3.js +++ b/assets/js/509d2004.1a6cb1b3.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"version-5.0/docs",previous:{title:"Custom annotations",permalink:"/docs/5.0/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/5.0/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function g(e){let{components:a,...n}=e;return(0,r.yg)(d,(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".'))}g.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"version-5.0/docs",previous:{title:"Custom annotations",permalink:"/docs/5.0/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/5.0/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function g(e){let{components:a,...n}=e;return(0,r.yg)(d,(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".'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5285d58e.92cac4ae.js b/assets/js/5285d58e.a659173f.js similarity index 99% rename from assets/js/5285d58e.92cac4ae.js rename to assets/js/5285d58e.a659173f.js index 800a8019f..c2bedf8aa 100644 --- a/assets/js/5285d58e.92cac4ae.js +++ b/assets/js/5285d58e.a659173f.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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.c60be34d.js b/assets/js/528fe65e.722571e6.js similarity index 99% rename from assets/js/528fe65e.c60be34d.js rename to assets/js/528fe65e.722571e6.js index bdded0206..eeee3476e 100644 --- a/assets/js/528fe65e.c60be34d.js +++ b/assets/js/528fe65e.722571e6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1027],{65009:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>l,contentTitle:()=>s,default:()=>c,frontMatter:()=>i,metadata:()=>r,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"},s=void 0,r={unversionedId:"type-mapping",id:"type-mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/docs/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/next/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/type-mapping.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"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:"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:()=>s,default:()=>c,frontMatter:()=>i,metadata:()=>r,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"},s=void 0,r={unversionedId:"type-mapping",id:"type-mapping",title:"Type mapping",description:"As explained in the queries section, the job of GraphQLite is to create GraphQL types from PHP types.",source:"@site/docs/type-mapping.mdx",sourceDirName:".",slug:"/type-mapping",permalink:"/docs/next/type-mapping",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/type-mapping.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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:"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:"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.9c598b07.js b/assets/js/54c144e4.bb6063dc.js similarity index 96% rename from assets/js/54c144e4.9c598b07.js rename to assets/js/54c144e4.bb6063dc.js index 267df7eb9..f48603cad 100644 --- a/assets/js/54c144e4.9c598b07.js +++ b/assets/js/54c144e4.bb6063dc.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.de282c9d.js b/assets/js/54ca8693.d08449f0.js similarity index 98% rename from assets/js/54ca8693.de282c9d.js rename to assets/js/54ca8693.d08449f0.js index f78b89aed..bdb47f2d7 100644 --- a/assets/js/54ca8693.de282c9d.js +++ b/assets/js/54ca8693.d08449f0.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.9367e8fe.js b/assets/js/56279b5e.668f312e.js similarity index 99% rename from assets/js/56279b5e.9367e8fe.js rename to assets/js/56279b5e.668f312e.js index a498519a3..c4b0413dd 100644 --- a/assets/js/56279b5e.9367e8fe.js +++ b/assets/js/56279b5e.668f312e.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.249b1f26.js b/assets/js/565a5567.933d5222.js similarity index 98% rename from assets/js/565a5567.249b1f26.js rename to assets/js/565a5567.933d5222.js index 29d87dbe4..f73ad1287 100644 --- a/assets/js/565a5567.249b1f26.js +++ b/assets/js/565a5567.933d5222.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:()=>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"},r=void 0,s={unversionedId:"doctrine-annotations-attributes",id:"version-4.0/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-4.0/doctrine_annotations_attributes.md",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/4.0/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/doctrine_annotations_attributes.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"}},l={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],u={toc:p},d="wrapper";function c(t){let{components:e,...n}=t;return(0,i.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.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")))}c.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:()=>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"},r=void 0,s={unversionedId:"doctrine-annotations-attributes",id:"version-4.0/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-4.0/doctrine_annotations_attributes.md",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/4.0/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/doctrine_annotations_attributes.md",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"}},l={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],u={toc:p},d="wrapper";function c(t){let{components:e,...n}=t;return(0,i.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.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")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/56af72f6.5b19550c.js b/assets/js/56af72f6.e60a700d.js similarity index 99% rename from assets/js/56af72f6.5b19550c.js rename to assets/js/56af72f6.e60a700d.js index a8b29d974..eef3f7ebf 100644 --- a/assets/js/56af72f6.5b19550c.js +++ b/assets/js/56af72f6.e60a700d.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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-system/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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-system/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.1f23575a.js b/assets/js/5792f9ba.00b9b662.js similarity index 98% rename from assets/js/5792f9ba.1f23575a.js rename to assets/js/5792f9ba.00b9b662.js index 1f617a45f..0d79fa64b 100644 --- a/assets/js/5792f9ba.1f23575a.js +++ b/assets/js/5792f9ba.00b9b662.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ed347d2a.js b/assets/js/579cc8d4.1da1a812.js similarity index 98% rename from assets/js/579cc8d4.ed347d2a.js rename to assets/js/579cc8d4.1da1a812.js index 3910389ef..b124b4d09 100644 --- a/assets/js/579cc8d4.ed347d2a.js +++ b/assets/js/579cc8d4.1da1a812.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:()=>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-3.0/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package",source:"@site/versioned_docs/version-3.0/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/3.0/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/implementing-security.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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},g="wrapper";function h(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/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")))}h.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:()=>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-3.0/implementing-security",title:"Connecting GraphQLite to your framework's security module",description:"This step is NOT necessary for users using GraphQLite through the Symfony Bundle or the Laravel package",source:"@site/versioned_docs/version-3.0/implementing-security.md",sourceDirName:".",slug:"/implementing-security",permalink:"/docs/3.0/implementing-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/implementing-security.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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},g="wrapper";function h(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/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")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/57f5c28c.6e73b6ce.js b/assets/js/57f5c28c.6aacba73.js similarity index 99% rename from assets/js/57f5c28c.6e73b6ce.js rename to assets/js/57f5c28c.6aacba73.js index 483784fb9..9ff6a7625 100644 --- a/assets/js/57f5c28c.6e73b6ce.js +++ b/assets/js/57f5c28c.6aacba73.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8372],{93300:(e,n,a)=>{a.r(n),a.d(n,{assets:()=>s,contentTitle:()=>i,default:()=>u,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-4.0/other-frameworks",title:"Getting started with any framework",description:"If you are using Symfony 4.x, checkout the Symfony bundle.",source:"@site/versioned_docs/version-4.0/other_frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/4.0/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/other_frameworks.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},sidebar:"version-4.0/docs",previous:{title:"Universal service providers",permalink:"/docs/4.0/universal_service_providers"},next:{title:"Queries",permalink:"/docs/4.0/queries"}},s={},p=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],c={toc:p},d="wrapper";function u(e){let{components:n,...o}=e;return(0,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:()=>s,contentTitle:()=>i,default:()=>u,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-4.0/other-frameworks",title:"Getting started with any framework",description:"If you are using Symfony 4.x, checkout the Symfony bundle.",source:"@site/versioned_docs/version-4.0/other_frameworks.mdx",sourceDirName:".",slug:"/other-frameworks",permalink:"/docs/4.0/other-frameworks",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.0/other_frameworks.mdx",tags:[],version:"4.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"other-frameworks",title:"Getting started with any framework",sidebar_label:"Other frameworks / No framework",original_id:"other-frameworks"},sidebar:"version-4.0/docs",previous:{title:"Universal service providers",permalink:"/docs/4.0/universal_service_providers"},next:{title:"Queries",permalink:"/docs/4.0/queries"}},s={},p=[{value:"Installation",id:"installation",level:2},{value:"Requirements",id:"requirements",level:2},{value:"Integration",id:"integration",level:2},{value:"GraphQLite context",id:"graphqlite-context",level:3},{value:"Minimal example",id:"minimal-example",level:2},{value:"PSR-15 Middleware",id:"psr-15-middleware",level:2},{value:"Example",id:"example",level:3}],c={toc:p},d="wrapper";function u(e){let{components:n,...o}=e;return(0,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.00fefab5.js b/assets/js/5881f7ec.9163213f.js similarity index 99% rename from assets/js/5881f7ec.00fefab5.js rename to assets/js/5881f7ec.9163213f.js index 3d56d5952..502db9bdc 100644 --- a/assets/js/5881f7ec.00fefab5.js +++ b/assets/js/5881f7ec.9163213f.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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/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.57520c92.js b/assets/js/58d52345.26ba55c3.js similarity index 97% rename from assets/js/58d52345.57520c92.js rename to assets/js/58d52345.26ba55c3.js index 404ee2f92..29ae92103 100644 --- a/assets/js/58d52345.57520c92.js +++ b/assets/js/58d52345.26ba55c3.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:()=>d});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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"features",slug:"/",title:"GraphQLite",sidebar_label:"GraphQLite",original_id:"features"},sidebar:"version-4.0/docs",next:{title:"Getting Started",permalink:"/docs/4.0/getting-started"}},o={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],u={toc:d},p="wrapper";function c(e){let{components:t,...a}=e;return(0,n.yg)(p,(0,r.A)({},u,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:()=>d});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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"features",slug:"/",title:"GraphQLite",sidebar_label:"GraphQLite",original_id:"features"},sidebar:"version-4.0/docs",next:{title:"Getting Started",permalink:"/docs/4.0/getting-started"}},o={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],u={toc:d},p="wrapper";function c(e){let{components:t,...a}=e;return(0,n.yg)(p,(0,r.A)({},u,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.6820b216.js b/assets/js/58e6b30f.2faed412.js similarity index 99% rename from assets/js/58e6b30f.6820b216.js rename to assets/js/58e6b30f.2faed412.js index e92019ef2..3058a3347 100644 --- a/assets/js/58e6b30f.6820b216.js +++ b/assets/js/58e6b30f.2faed412.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.e70e6fa1.js b/assets/js/5945e8b0.efe55108.js similarity index 99% rename from assets/js/5945e8b0.e70e6fa1.js rename to assets/js/5945e8b0.efe55108.js index 04fd2440b..34b08acef 100644 --- a/assets/js/5945e8b0.e70e6fa1.js +++ b/assets/js/5945e8b0.efe55108.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ce6f95a4.js b/assets/js/5a9b411c.559a6713.js similarity index 99% rename from assets/js/5a9b411c.ce6f95a4.js rename to assets/js/5a9b411c.559a6713.js index 1477bdb82..7d24f0993 100644 --- a/assets/js/5a9b411c.ce6f95a4.js +++ b/assets/js/5a9b411c.559a6713.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/5bc7272e.0771ddb5.js b/assets/js/5bc7272e.980951c9.js similarity index 99% rename from assets/js/5bc7272e.0771ddb5.js rename to assets/js/5bc7272e.980951c9.js index 42de3302d..461a566f7 100644 --- a/assets/js/5bc7272e.0771ddb5.js +++ b/assets/js/5bc7272e.980951c9.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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([[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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/5d7590c2.d21d7c9f.js b/assets/js/5d7590c2.bc73a967.js similarity index 98% rename from assets/js/5d7590c2.d21d7c9f.js rename to assets/js/5d7590c2.bc73a967.js index ddb30d37e..ac4332ce1 100644 --- a/assets/js/5d7590c2.d21d7c9f.js +++ b/assets/js/5d7590c2.bc73a967.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/5dde70bf.fcf84c6a.js b/assets/js/5dde70bf.b5740b86.js similarity index 99% rename from assets/js/5dde70bf.fcf84c6a.js rename to assets/js/5dde70bf.b5740b86.js index ec9b21e82..01e9bd6e1 100644 --- a/assets/js/5dde70bf.fcf84c6a.js +++ b/assets/js/5dde70bf.b5740b86.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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-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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"'},"{n.r(a),n.d(a,{assets:()=>p,contentTitle:()=>o,default:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 d(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"),"."))}d.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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 d(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"),"."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/5e352ef4.7431f3bd.js b/assets/js/5e352ef4.cec79076.js similarity index 99% rename from assets/js/5e352ef4.7431f3bd.js rename to assets/js/5e352ef4.cec79076.js index e5b8bbbb8..62784f15e 100644 --- a/assets/js/5e352ef4.7431f3bd.js +++ b/assets/js/5e352ef4.cec79076.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.cd22f35c.js b/assets/js/5e457383.24cd44b0.js similarity index 98% rename from assets/js/5e457383.cd22f35c.js rename to assets/js/5e457383.24cd44b0.js index 6877c2a97..36862a447 100644 --- a/assets/js/5e457383.cd22f35c.js +++ b/assets/js/5e457383.24cd44b0.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Annotations reference",permalink:"/docs/annotations-reference"},next:{title:"Changelog",permalink:"/docs/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components: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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning"},sidebar:"docs",previous:{title:"Annotations reference",permalink:"/docs/annotations-reference"},next:{title:"Changelog",permalink:"/docs/changelog"}},l={},p=[],m={toc:p},u="wrapper";function c(e){let{components: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.75d547c0.js b/assets/js/5ec7a7fe.9f7d2515.js similarity index 99% rename from assets/js/5ec7a7fe.75d547c0.js rename to assets/js/5ec7a7fe.9f7d2515.js index 5ce57a4a6..1f82205b6 100644 --- a/assets/js/5ec7a7fe.75d547c0.js +++ b/assets/js/5ec7a7fe.9f7d2515.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.321e03dd.js b/assets/js/5ececfab.81c29f92.js similarity index 99% rename from assets/js/5ececfab.321e03dd.js rename to assets/js/5ececfab.81c29f92.js index 65fdcf491..97c8a7775 100644 --- a/assets/js/5ececfab.321e03dd.js +++ b/assets/js/5ececfab.81c29f92.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 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))}},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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}],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/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 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))}},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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}],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/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.4a59bbf6.js b/assets/js/5fa4a5b6.0c5693e2.js similarity index 99% rename from assets/js/5fa4a5b6.4a59bbf6.js rename to assets/js/5fa4a5b6.0c5693e2.js index ec5236739..f097bb6ab 100644 --- a/assets/js/5fa4a5b6.4a59bbf6.js +++ b/assets/js/5fa4a5b6.0c5693e2.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 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))}},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features",original_id:"symfony-bundle-advanced"},sidebar:"version-4.1/docs",previous:{title:"Class with multiple output types",permalink:"/docs/4.1/multiple_output_types"},next:{title:"Laravel specific features",permalink:"/docs/4.1/laravel-package-advanced"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:p},m="wrapper";function g(e){let{components:n,...t}=e;return(0,l.yg)(m,(0,a.A)({},d,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 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))}},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features",original_id:"symfony-bundle-advanced"},sidebar:"version-4.1/docs",previous:{title:"Class with multiple output types",permalink:"/docs/4.1/multiple_output_types"},next:{title:"Laravel specific features",permalink:"/docs/4.1/laravel-package-advanced"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],d={toc:p},m="wrapper";function g(e){let{components:n,...t}=e;return(0,l.yg)(m,(0,a.A)({},d,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/5ffc8074.41ae9a58.js b/assets/js/5ffc8074.382b4640.js similarity index 99% rename from assets/js/5ffc8074.41ae9a58.js rename to assets/js/5ffc8074.382b4640.js index 45db01453..bccabe98b 100644 --- a/assets/js/5ffc8074.41ae9a58.js +++ b/assets/js/5ffc8074.382b4640.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.12b37f8d.js b/assets/js/606959d6.2d95a4c6.js similarity index 99% rename from assets/js/606959d6.12b37f8d.js rename to assets/js/606959d6.2d95a4c6.js index 3ecd9519d..b20d4585e 100644 --- a/assets/js/606959d6.12b37f8d.js +++ b/assets/js/606959d6.2d95a4c6.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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/60d99771.6eee9b87.js b/assets/js/60d99771.ac4342ef.js similarity index 98% rename from assets/js/60d99771.6eee9b87.js rename to assets/js/60d99771.ac4342ef.js index 464ae0867..af272ad0c 100644 --- a/assets/js/60d99771.6eee9b87.js +++ b/assets/js/60d99771.ac4342ef.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.d2835569.js b/assets/js/610e7425.22b083d8.js similarity index 99% rename from assets/js/610e7425.d2835569.js rename to assets/js/610e7425.22b083d8.js index 87b2b90cd..2fec53789 100644 --- a/assets/js/610e7425.d2835569.js +++ b/assets/js/610e7425.22b083d8.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:()=>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"},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 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"},"#[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")))}d.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:()=>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"},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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 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"},"#[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")))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/612b773e.7d6b0229.js b/assets/js/612b773e.e479b012.js similarity index 96% rename from assets/js/612b773e.7d6b0229.js rename to assets/js/612b773e.e479b012.js index 9fa1fb5da..fa00bd4df 100644 --- a/assets/js/612b773e.7d6b0229.js +++ b/assets/js/612b773e.e479b012.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:()=>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:"mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/docs/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/next/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/mutations.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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={},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/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:()=>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:"mutations",title:"Mutations",description:"In GraphQLite, mutations are created like queries.",source:"@site/docs/mutations.mdx",sourceDirName:".",slug:"/mutations",permalink:"/docs/next/mutations",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/mutations.mdx",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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={},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/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.74330fc8.js b/assets/js/61595218.ebfdff1a.js similarity index 99% rename from assets/js/61595218.74330fc8.js rename to assets/js/61595218.ebfdff1a.js index ce47c45fd..3c9c75695 100644 --- a/assets/js/61595218.74330fc8.js +++ b/assets/js/61595218.ebfdff1a.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.88a4d717.js b/assets/js/617523b3.79ae2a0c.js similarity index 99% rename from assets/js/617523b3.88a4d717.js rename to assets/js/617523b3.79ae2a0c.js index 534a3ca61..f041b125f 100644 --- a/assets/js/617523b3.88a4d717.js +++ b/assets/js/617523b3.79ae2a0c.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),p=a(57485),o=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,o.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,p.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}))),[p,o]=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=p??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),o(e),h(e)}),[o,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:p,tabValues:o}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.a_)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=o[a].value;n!==i&&(d(t),p(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)},o.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:()=>p,default:()=>m,frontMatter:()=>i,metadata:()=>o,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"},p=void 0,o={unversionedId:"multiple_output_types",id:"version-4.1/multiple_output_types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.1/multiple_output_types.mdx",sourceDirName:".",slug:"/multiple_output_types",permalink:"/docs/4.1/multiple_output_types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/multiple_output_types.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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),p=a(57485),o=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,o.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,p.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}))),[p,o]=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=p??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),o(e),h(e)}),[o,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:p,tabValues:o}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.a_)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=o[a].value;n!==i&&(d(t),p(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)},o.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:()=>p,default:()=>m,frontMatter:()=>i,metadata:()=>o,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"},p=void 0,o={unversionedId:"multiple_output_types",id:"version-4.1/multiple_output_types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-4.1/multiple_output_types.mdx",sourceDirName:".",slug:"/multiple_output_types",permalink:"/docs/4.1/multiple_output_types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/multiple_output_types.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ddc67bf7.js b/assets/js/61c7d915.0a2b168b.js similarity index 98% rename from assets/js/61c7d915.ddc67bf7.js rename to assets/js/61c7d915.0a2b168b.js index 2dce0ff02..c779704a7 100644 --- a/assets/js/61c7d915.ddc67bf7.js +++ b/assets/js/61c7d915.0a2b168b.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.bc73ad97.js b/assets/js/623b6c78.d7c4e3d8.js similarity index 99% rename from assets/js/623b6c78.bc73ad97.js rename to assets/js/623b6c78.d7c4e3d8.js index 3408f7b3f..f314d509b 100644 --- a/assets/js/623b6c78.bc73ad97.js +++ b/assets/js/623b6c78.d7c4e3d8.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.07bf472c.js b/assets/js/64536e1a.e0906f5a.js similarity index 99% rename from assets/js/64536e1a.07bf472c.js rename to assets/js/64536e1a.e0906f5a.js index 849f97ae0..e94f401b9 100644 --- a/assets/js/64536e1a.07bf472c.js +++ b/assets/js/64536e1a.e0906f5a.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ed002f1f.js b/assets/js/64947e00.ec66addf.js similarity index 99% rename from assets/js/64947e00.ed002f1f.js rename to assets/js/64947e00.ec66addf.js index 9f64f3991..fc2dfd49b 100644 --- a/assets/js/64947e00.ed002f1f.js +++ b/assets/js/64947e00.ec66addf.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.3e38ddd7.js b/assets/js/652c74f1.6359bb26.js similarity index 99% rename from assets/js/652c74f1.3e38ddd7.js rename to assets/js/652c74f1.6359bb26.js index db147e613..7785d5c67 100644 --- a/assets/js/652c74f1.3e38ddd7.js +++ b/assets/js/652c74f1.6359bb26.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.8d1b90a0.js b/assets/js/65b8d1d1.d8e12cac.js similarity index 99% rename from assets/js/65b8d1d1.8d1b90a0.js rename to assets/js/65b8d1d1.d8e12cac.js index 195439124..c8cfe2dde 100644 --- a/assets/js/65b8d1d1.8d1b90a0.js +++ b/assets/js/65b8d1d1.d8e12cac.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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([[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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/673df5d6.895ad17e.js b/assets/js/673df5d6.a9b22576.js similarity index 99% rename from assets/js/673df5d6.895ad17e.js rename to assets/js/673df5d6.a9b22576.js index 30408f37f..2a15d8514 100644 --- a/assets/js/673df5d6.895ad17e.js +++ b/assets/js/673df5d6.a9b22576.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.07386ae0.js b/assets/js/68b7d615.9c5c0e30.js similarity index 99% rename from assets/js/68b7d615.07386ae0.js rename to assets/js/68b7d615.9c5c0e30.js index 25e75a7e8..04e93732b 100644 --- a/assets/js/68b7d615.07386ae0.js +++ b/assets/js/68b7d615.9c5c0e30.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.fe37ea89.js b/assets/js/68e30702.5028a35e.js similarity index 98% rename from assets/js/68e30702.fe37ea89.js rename to assets/js/68e30702.5028a35e.js index 7b4fb0776..1c4ad9a29 100644 --- a/assets/js/68e30702.fe37ea89.js +++ b/assets/js/68e30702.5028a35e.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}),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))}},24351:(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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/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}),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))}},24351:(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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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/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.051152f6.js b/assets/js/69f2ab1f.8ca20958.js similarity index 99% rename from assets/js/69f2ab1f.051152f6.js rename to assets/js/69f2ab1f.8ca20958.js index a62706cbb..2b8c6c61d 100644 --- a/assets/js/69f2ab1f.051152f6.js +++ b/assets/js/69f2ab1f.8ca20958.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.3340519d.js b/assets/js/6a8c9872.7ccea129.js similarity index 99% rename from assets/js/6a8c9872.3340519d.js rename to assets/js/6a8c9872.7ccea129.js index 202109505..bd5429155 100644 --- a/assets/js/6a8c9872.3340519d.js +++ b/assets/js/6a8c9872.7ccea129.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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.27875216.js b/assets/js/6ad31330.e6d3127b.js similarity index 97% rename from assets/js/6ad31330.27875216.js rename to assets/js/6ad31330.e6d3127b.js index 06861a9df..c47c45050 100644 --- a/assets/js/6ad31330.27875216.js +++ b/assets/js/6ad31330.e6d3127b.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"version-5.0/docs",previous:{title:"GraphQLite",permalink:"/docs/5.0/"},next:{title:"Symfony bundle",permalink:"/docs/5.0/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},p,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)"))))}g.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"version-5.0/docs",previous:{title:"GraphQLite",permalink:"/docs/5.0/"},next:{title:"Symfony bundle",permalink:"/docs/5.0/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},p,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)"))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6c124661.7cbe5021.js b/assets/js/6c124661.ef09a451.js similarity index 98% rename from assets/js/6c124661.7cbe5021.js rename to assets/js/6c124661.ef09a451.js index 4cbc60f35..21b50c459 100644 --- a/assets/js/6c124661.7cbe5021.js +++ b/assets/js/6c124661.ef09a451.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.d3c7ec0b.js b/assets/js/6c14a231.1d305f75.js similarity index 99% rename from assets/js/6c14a231.d3c7ec0b.js rename to assets/js/6c14a231.1d305f75.js index 55ad0a2f9..b8140d000 100644 --- a/assets/js/6c14a231.d3c7ec0b.js +++ b/assets/js/6c14a231.1d305f75.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 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 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=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=g({queryString:a,groupId:n}),[d,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??d;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:d}=(0,u.a_)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.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:p},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:()=>d});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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"version-5.0/docs",next:{title:"Getting Started",permalink:"/docs/5.0/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(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)(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 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 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=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=g({queryString:a,groupId:n}),[d,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??d;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:d}=(0,u.a_)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.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:p},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:()=>d});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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"version-5.0/docs",next:{title:"Getting Started",permalink:"/docs/5.0/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(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)(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.1aaa0aca.js b/assets/js/6c4340be.df1dad05.js similarity index 99% rename from assets/js/6c4340be.1aaa0aca.js rename to assets/js/6c4340be.df1dad05.js index 586699027..0ca00c6ff 100644 --- a/assets/js/6c4340be.1aaa0aca.js +++ b/assets/js/6c4340be.df1dad05.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/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/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([[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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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/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/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/6c6ce37c.00a01a79.js b/assets/js/6c6ce37c.9f1a930b.js similarity index 97% rename from assets/js/6c6ce37c.00a01a79.js rename to assets/js/6c6ce37c.9f1a930b.js index c9f2bc33d..b71103560 100644 --- a/assets/js/6c6ce37c.00a01a79.js +++ b/assets/js/6c6ce37c.9f1a930b.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"version-4.2/docs",previous:{title:"Internals",permalink:"/docs/4.2/internals"},next:{title:"Migrating",permalink:"/docs/4.2/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},p,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."))}d.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"version-4.2/docs",previous:{title:"Internals",permalink:"/docs/4.2/internals"},next:{title:"Migrating",permalink:"/docs/4.2/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},p,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."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/6cfcfcfb.538269ec.js b/assets/js/6cfcfcfb.d44b9f3a.js similarity index 99% rename from assets/js/6cfcfcfb.538269ec.js rename to assets/js/6cfcfcfb.d44b9f3a.js index c3e442cf5..eab6379c3 100644 --- a/assets/js/6cfcfcfb.538269ec.js +++ b/assets/js/6cfcfcfb.d44b9f3a.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.0ed36bbc.js b/assets/js/6d89025c.2bba48c9.js similarity index 99% rename from assets/js/6d89025c.0ed36bbc.js rename to assets/js/6d89025c.2bba48c9.js index 818bd5adf..d85e85df5 100644 --- a/assets/js/6d89025c.0ed36bbc.js +++ b/assets/js/6d89025c.2bba48c9.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1190],{19365:(e,t,n)=>{n.d(t,{A:()=>u});var a=n(96540),l=n(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>N});var a=n(58168),l=n(96540),r=n(20053),u=n(23104),o=n(56347),i=n(57485),s=n(31682),c=n(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.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 m(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,i.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 y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=g({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Dv)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,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=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.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,r.A)("tabs__item",f.tabItem,u?.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 q(e){const t=y(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 N(e){const t=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(t)},e))}},62141:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(58168),l=(n(96540),n(15680)),r=(n(67443),n(11470)),u=n(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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:t,...n}=e;return(0,l.yg)(m,(0,a.A)({},d,n,{components:t,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,t,n)=>{n.d(t,{A:()=>u});var a=n(96540),l=n(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>N});var a=n(58168),l=n(96540),r=n(20053),u=n(23104),o=n(56347),i=n(57485),s=n(31682),c=n(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.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 m(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,i.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 y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=g({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Dv)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,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=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.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,r.A)("tabs__item",f.tabItem,u?.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 q(e){const t=y(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 N(e){const t=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(t)},e))}},62141:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(58168),l=(n(96540),n(15680)),r=(n(67443),n(11470)),u=n(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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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:t,...n}=e;return(0,l.yg)(m,(0,a.A)({},d,n,{components:t,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.054a55e6.js b/assets/js/6efd6ec9.7ee75f12.js similarity index 99% rename from assets/js/6efd6ec9.054a55e6.js rename to assets/js/6efd6ec9.7ee75f12.js index ea9c87ea9..c7c29f71e 100644 --- a/assets/js/6efd6ec9.054a55e6.js +++ b/assets/js/6efd6ec9.7ee75f12.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.63909169.js b/assets/js/6fe30f11.1772048a.js similarity index 98% rename from assets/js/6fe30f11.63909169.js rename to assets/js/6fe30f11.1772048a.js index 01d7cf75e..6a754084f 100644 --- a/assets/js/6fe30f11.63909169.js +++ b/assets/js/6fe30f11.1772048a.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.30d486bb.js b/assets/js/71a56230.2f5cd36c.js similarity index 97% rename from assets/js/71a56230.30d486bb.js rename to assets/js/71a56230.2f5cd36c.js index dda010fd9..448e64347 100644 --- a/assets/js/71a56230.30d486bb.js +++ b/assets/js/71a56230.2f5cd36c.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:()=>c,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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},p="wrapper";function c(e){let{components:t,...o}=e;return(0,r.yg)(p,(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."))}c.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:()=>c,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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},p="wrapper";function c(e){let{components:t,...o}=e;return(0,r.yg)(p,(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."))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/72be5fd7.72da73d5.js b/assets/js/72be5fd7.5f11d860.js similarity index 99% rename from assets/js/72be5fd7.72da73d5.js rename to assets/js/72be5fd7.5f11d860.js index 8b6e0a2c3..9859a8a34 100644 --- a/assets/js/72be5fd7.72da73d5.js +++ b/assets/js/72be5fd7.5f11d860.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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={},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/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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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={},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/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.8a2fadd5.js b/assets/js/72d0dc3a.757595fe.js similarity index 97% rename from assets/js/72d0dc3a.8a2fadd5.js rename to assets/js/72d0dc3a.757595fe.js index 2d0758316..020b1e57f 100644 --- a/assets/js/72d0dc3a.8a2fadd5.js +++ b/assets/js/72d0dc3a.757595fe.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"version-4.3/docs",previous:{title:"Internals",permalink:"/docs/4.3/internals"},next:{title:"Migrating",permalink:"/docs/4.3/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},p,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."))}d.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"version-4.3/docs",previous:{title:"Internals",permalink:"/docs/4.3/internals"},next:{title:"Migrating",permalink:"/docs/4.3/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},p,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."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/741df2ae.d7ee228b.js b/assets/js/741df2ae.8def9ec7.js similarity index 99% rename from assets/js/741df2ae.d7ee228b.js rename to assets/js/741df2ae.8def9ec7.js index e32bb1759..1768d9b17 100644 --- a/assets/js/741df2ae.d7ee228b.js +++ b/assets/js/741df2ae.8def9ec7.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.36d2c5e5.js b/assets/js/74383bd8.52f7baf7.js similarity index 99% rename from assets/js/74383bd8.36d2c5e5.js rename to assets/js/74383bd8.52f7baf7.js index fb48ed54b..f042826d4 100644 --- a/assets/js/74383bd8.36d2c5e5.js +++ b/assets/js/74383bd8.52f7baf7.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.3c6e0fa6.js b/assets/js/7515d7ec.cd92088e.js similarity index 99% rename from assets/js/7515d7ec.3c6e0fa6.js rename to assets/js/7515d7ec.cd92088e.js index 558d2f0df..9bfa3aa40 100644 --- a/assets/js/7515d7ec.3c6e0fa6.js +++ b/assets/js/7515d7ec.cd92088e.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.182b31ca.js b/assets/js/756c6ac7.c578852e.js similarity index 99% rename from assets/js/756c6ac7.182b31ca.js rename to assets/js/756c6ac7.c578852e.js index 1a07f22c9..df1ffc738 100644 --- a/assets/js/756c6ac7.182b31ca.js +++ b/assets/js/756c6ac7.c578852e.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.435bc032.js b/assets/js/75cc8326.3c8456bf.js similarity index 99% rename from assets/js/75cc8326.435bc032.js rename to assets/js/75cc8326.3c8456bf.js index b2891e1da..b083460e1 100644 --- a/assets/js/75cc8326.435bc032.js +++ b/assets/js/75cc8326.3c8456bf.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.007f2971.js b/assets/js/766e1cc8.5884e667.js similarity index 99% rename from assets/js/766e1cc8.007f2971.js rename to assets/js/766e1cc8.5884e667.js index 0c6571b08..7804f31d9 100644 --- a/assets/js/766e1cc8.007f2971.js +++ b/assets/js/766e1cc8.5884e667.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ec7dc3fc.js b/assets/js/767c28af.076047b9.js similarity index 99% rename from assets/js/767c28af.ec7dc3fc.js rename to assets/js/767c28af.076047b9.js index 9109c03e9..6c0b60275 100644 --- a/assets/js/767c28af.ec7dc3fc.js +++ b/assets/js/767c28af.076047b9.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.979607ae.js b/assets/js/77cdcd82.121eed95.js similarity index 97% rename from assets/js/77cdcd82.979607ae.js rename to assets/js/77cdcd82.121eed95.js index 494b530c2..baf8484a8 100644 --- a/assets/js/77cdcd82.979607ae.js +++ b/assets/js/77cdcd82.121eed95.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},p,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."))}d.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},p,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."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7810a993.263785f9.js b/assets/js/7810a993.16409b83.js similarity index 99% rename from assets/js/7810a993.263785f9.js rename to assets/js/7810a993.16409b83.js index 4e412eb27..379c40703 100644 --- a/assets/js/7810a993.263785f9.js +++ b/assets/js/7810a993.16409b83.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9271],{19365:(e,t,n)=>{n.d(t,{A:()=>u});var a=n(96540),l=n(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>N});var a=n(58168),l=n(96540),r=n(20053),u=n(23104),o=n(56347),i=n(57485),s=n(31682),c=n(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.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 m(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,i.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 y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=g({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Dv)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,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=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.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,r.A)("tabs__item",f.tabItem,u?.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 q(e){const t=y(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 N(e){const t=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(t)},e))}},84534:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(58168),l=(n(96540),n(15680)),r=(n(67443),n(11470)),u=n(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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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:t,...n}=e;return(0,l.yg)(m,(0,a.A)({},d,n,{components:t,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,t,n)=>{n.d(t,{A:()=>u});var a=n(96540),l=n(20053);const r={tabItem:"tabItem_Ymn6"};function u(e){let{children:t,hidden:n,className:u}=e;return a.createElement("div",{role:"tabpanel",className:(0,l.A)(r.tabItem,u),hidden:n},t)}},11470:(e,t,n)=>{n.d(t,{A:()=>N});var a=n(58168),l=n(96540),r=n(20053),u=n(23104),o=n(56347),i=n(57485),s=n(31682),c=n(89466);function p(e){return function(e){return l.Children.map(e,(e=>{if(!e||(0,l.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the component should be , and every should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:l}}=e;return{value:t,label:n,attributes:a,default:l}}))}function d(e){const{values:t,children:n}=e;return(0,l.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,s.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 m(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,i.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 y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,r=d(e),[u,o]=(0,l.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:r}))),[i,s]=g({queryString:n,groupId:a}),[p,y]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,r]=(0,c.Dv)(n);return[a,(0,l.useCallback)((e=>{n&&r.set(e)}),[n,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=n(92303);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:o,selectValue:i,tabValues:s}=e;const c=[],{blockElementScrollPositionUntilNextRender:p}=(0,u.a_)(),d=e=>{const t=e.currentTarget,n=c.indexOf(t),a=s[n].value;a!==o&&(p(t),i(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return l.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,r.A)("tabs",{"tabs--block":n},t)},s.map((e=>{let{value:t,label:n,attributes:u}=e;return l.createElement("li",(0,a.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,r.A)("tabs__item",f.tabItem,u?.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 q(e){const t=y(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 N(e){const t=(0,h.A)();return l.createElement(q,(0,a.A)({key:String(t)},e))}},84534:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>g,frontMatter:()=>o,metadata:()=>s,toc:()=>p});var a=n(58168),l=(n(96540),n(15680)),r=(n(67443),n(11470)),u=n(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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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:t,...n}=e;return(0,l.yg)(m,(0,a.A)({},d,n,{components:t,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.5a6df041.js b/assets/js/78619623.2a48f5b2.js similarity index 99% rename from assets/js/78619623.5a6df041.js rename to assets/js/78619623.2a48f5b2.js index 86a58416b..944b30204 100644 --- a/assets/js/78619623.5a6df041.js +++ b/assets/js/78619623.2a48f5b2.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.8e7ba28c.js b/assets/js/78da31a1.81a56c02.js similarity index 99% rename from assets/js/78da31a1.8e7ba28c.js rename to assets/js/78da31a1.81a56c02.js index 2c9b96c38..238c5f94f 100644 --- a/assets/js/78da31a1.8e7ba28c.js +++ b/assets/js/78da31a1.81a56c02.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/7afb60b1.a34d9d6f.js b/assets/js/7afb60b1.1b724298.js similarity index 99% rename from assets/js/7afb60b1.a34d9d6f.js rename to assets/js/7afb60b1.1b724298.js index b0742258d..b497f9678 100644 --- a/assets/js/7afb60b1.a34d9d6f.js +++ b/assets/js/7afb60b1.1b724298.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),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 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:()=>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-4.3/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-4.3/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/4.3/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/error-handling.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"version-4.3/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/4.3/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/4.3/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function 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),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 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:()=>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-4.3/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-4.3/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/4.3/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/error-handling.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"version-4.3/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/4.3/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/4.3/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function 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/7b54f5d5.b5df9ba2.js b/assets/js/7b54f5d5.ad75730f.js similarity index 99% rename from assets/js/7b54f5d5.b5df9ba2.js rename to assets/js/7b54f5d5.ad75730f.js index 547f7e3fe..ff5b4405c 100644 --- a/assets/js/7b54f5d5.b5df9ba2.js +++ b/assets/js/7b54f5d5.ad75730f.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 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))}},71683:(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"},o=void 0,p={unversionedId:"multiple-output-types",id:"version-5.0/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-5.0/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/5.0/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/multiple-output-types.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"version-5.0/docs",previous:{title:"Extending an input type",permalink:"/docs/5.0/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/5.0/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},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/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 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))}},71683:(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"},o=void 0,p={unversionedId:"multiple-output-types",id:"version-5.0/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-5.0/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/5.0/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/multiple-output-types.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"version-5.0/docs",previous:{title:"Extending an input type",permalink:"/docs/5.0/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/5.0/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},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/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.02928b46.js b/assets/js/7bf967bc.76cb6139.js similarity index 98% rename from assets/js/7bf967bc.02928b46.js rename to assets/js/7bf967bc.76cb6139.js index 25a6ccb9b..889052dd7 100644 --- a/assets/js/7bf967bc.02928b46.js +++ b/assets/js/7bf967bc.76cb6139.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:()=>y,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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}],d={toc:s},r="wrapper";function y(e){let{components:t,...n}=e;return(0,l.yg)(r,(0,a.A)({},d,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."))}y.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:()=>y,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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}],d={toc:s},r="wrapper";function y(e){let{components:t,...n}=e;return(0,l.yg)(r,(0,a.A)({},d,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."))}y.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/7c27e34c.c005f810.js b/assets/js/7c27e34c.19b3c022.js similarity index 95% rename from assets/js/7c27e34c.c005f810.js rename to assets/js/7c27e34c.19b3c022.js index 469a83fbb..08820b538 100644 --- a/assets/js/7c27e34c.c005f810.js +++ b/assets/js/7c27e34c.19b3c022.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.672c2963.js b/assets/js/7e507331.604dcbe9.js similarity index 98% rename from assets/js/7e507331.672c2963.js rename to assets/js/7e507331.604dcbe9.js index 0d02b216b..58d185f01 100644 --- a/assets/js/7e507331.672c2963.js +++ b/assets/js/7e507331.604dcbe9.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.bc402124.js b/assets/js/7e63a40e.e9c65e4c.js similarity index 98% rename from assets/js/7e63a40e.bc402124.js rename to assets/js/7e63a40e.e9c65e4c.js index 1054c2a85..bf0273b9a 100644 --- a/assets/js/7e63a40e.bc402124.js +++ b/assets/js/7e63a40e.e9c65e4c.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.af9426ef.js b/assets/js/7ee46e43.ac809c54.js similarity index 98% rename from assets/js/7ee46e43.af9426ef.js rename to assets/js/7ee46e43.ac809c54.js index 1b3706a38..e55e80b42 100644 --- a/assets/js/7ee46e43.af9426ef.js +++ b/assets/js/7ee46e43.ac809c54.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/820db038.bdb67856.js b/assets/js/820db038.336d5a20.js similarity index 99% rename from assets/js/820db038.bdb67856.js rename to assets/js/820db038.336d5a20.js index 784039950..67de847b9 100644 --- a/assets/js/820db038.bdb67856.js +++ b/assets/js/820db038.336d5a20.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/822cd419.4bbdece7.js b/assets/js/822cd419.eec8322d.js similarity index 98% rename from assets/js/822cd419.4bbdece7.js rename to assets/js/822cd419.eec8322d.js index 2cd9a5ec4..ae6c0eecd 100644 --- a/assets/js/822cd419.4bbdece7.js +++ b/assets/js/822cd419.eec8322d.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.32f48466.js b/assets/js/82395e72.d158cad6.js similarity index 99% rename from assets/js/82395e72.32f48466.js rename to assets/js/82395e72.d158cad6.js index 45dc27290..8e80f64ea 100644 --- a/assets/js/82395e72.32f48466.js +++ b/assets/js/82395e72.d158cad6.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.5a2348ca.js b/assets/js/8299d165.45757bd5.js similarity index 99% rename from assets/js/8299d165.5a2348ca.js rename to assets/js/8299d165.45757bd5.js index e53b9ec27..693aaaeb1 100644 --- a/assets/js/8299d165.5a2348ca.js +++ b/assets/js/8299d165.45757bd5.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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.462347e3.js b/assets/js/843ebfb4.8680fd03.js similarity index 99% rename from assets/js/843ebfb4.462347e3.js rename to assets/js/843ebfb4.8680fd03.js index 5ae6a614c..5c7ac8b5f 100644 --- a/assets/js/843ebfb4.462347e3.js +++ b/assets/js/843ebfb4.8680fd03.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.0793324f.js b/assets/js/85339969.cf5cbbcf.js similarity index 99% rename from assets/js/85339969.0793324f.js rename to assets/js/85339969.cf5cbbcf.js index 29ccf7be7..d39d297c4 100644 --- a/assets/js/85339969.0793324f.js +++ b/assets/js/85339969.cf5cbbcf.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.614c1383.js b/assets/js/859fcda7.6f4e9cfc.js similarity index 97% rename from assets/js/859fcda7.614c1383.js rename to assets/js/859fcda7.6f4e9cfc.js index 4874bbd95..4dc533ed2 100644 --- a/assets/js/859fcda7.614c1383.js +++ b/assets/js/859fcda7.6f4e9cfc.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9810],{95499:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>c,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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},p="wrapper";function c(t){let{components:e,...a}=t;return(0,i.yg)(p,(0,r.A)({},g,a,{components:e,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)"))))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9810],{95499:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>c,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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},p="wrapper";function c(t){let{components:e,...a}=t;return(0,i.yg)(p,(0,r.A)({},g,a,{components:e,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)"))))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/85c72337.1def6368.js b/assets/js/85c72337.68dbbe79.js similarity index 99% rename from assets/js/85c72337.1def6368.js rename to assets/js/85c72337.68dbbe79.js index 863c054ea..f18e36343 100644 --- a/assets/js/85c72337.1def6368.js +++ b/assets/js/85c72337.68dbbe79.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.e0da2805.js b/assets/js/87089bce.c45cefa8.js similarity index 99% rename from assets/js/87089bce.e0da2805.js rename to assets/js/87089bce.c45cefa8.js index 9db538812..33822a2ca 100644 --- a/assets/js/87089bce.e0da2805.js +++ b/assets/js/87089bce.c45cefa8.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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.1b840764.js b/assets/js/8913b51a.099434fd.js similarity index 98% rename from assets/js/8913b51a.1b840764.js rename to assets/js/8913b51a.099434fd.js index 32efbc0af..a283035a0 100644 --- a/assets/js/8913b51a.1b840764.js +++ b/assets/js/8913b51a.099434fd.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.26a332e9.js b/assets/js/89cae3a7.f2f58bf0.js similarity index 99% rename from assets/js/89cae3a7.26a332e9.js rename to assets/js/89cae3a7.f2f58bf0.js index c0ce5bb2a..fdb540d90 100644 --- a/assets/js/89cae3a7.26a332e9.js +++ b/assets/js/89cae3a7.f2f58bf0.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.cdb311ab.js b/assets/js/89ed63c8.dab6893e.js similarity index 99% rename from assets/js/89ed63c8.cdb311ab.js rename to assets/js/89ed63c8.dab6893e.js index 76fd6e653..b62ff759d 100644 --- a/assets/js/89ed63c8.cdb311ab.js +++ b/assets/js/89ed63c8.dab6893e.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 p(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 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,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=p(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}))),[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 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),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_)(),p=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},h=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 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:h,onClick:p},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"version-4.3/docs",previous:{title:"User input validation",permalink:"/docs/4.3/validation"},next:{title:"Fine grained security",permalink:"/docs/4.3/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(h,(0,a.A)({},p,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 p(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 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,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=p(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}))),[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 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),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_)(),p=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},h=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 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:h,onClick:p},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"version-4.3/docs",previous:{title:"User input validation",permalink:"/docs/4.3/validation"},next:{title:"Fine grained security",permalink:"/docs/4.3/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(h,(0,a.A)({},p,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.c0ebbd9d.js b/assets/js/8b6bafea.d38cc5d5.js similarity index 98% rename from assets/js/8b6bafea.c0ebbd9d.js rename to assets/js/8b6bafea.d38cc5d5.js index c7095311b..60e341835 100644 --- a/assets/js/8b6bafea.c0ebbd9d.js +++ b/assets/js/8b6bafea.d38cc5d5.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2230],{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))}},74128:(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-5.0/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-5.0/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/5.0/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/prefetch-method.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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)(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([[2230],{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))}},74128:(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-5.0/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-5.0/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/5.0/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/prefetch-method.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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)(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/8bf32d27.5148b85d.js b/assets/js/8bf32d27.2de9f795.js similarity index 99% rename from assets/js/8bf32d27.5148b85d.js rename to assets/js/8bf32d27.2de9f795.js index 1013af8eb..d5b4f9040 100644 --- a/assets/js/8bf32d27.5148b85d.js +++ b/assets/js/8bf32d27.2de9f795.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.191afaf6.js b/assets/js/8c95fc16.8c929c5b.js similarity index 99% rename from assets/js/8c95fc16.191afaf6.js rename to assets/js/8c95fc16.8c929c5b.js index 01eab0d46..a0e79d70d 100644 --- a/assets/js/8c95fc16.191afaf6.js +++ b/assets/js/8c95fc16.8c929c5b.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.81c8237f.js b/assets/js/8d81badd.6701e780.js similarity index 99% rename from assets/js/8d81badd.81c8237f.js rename to assets/js/8d81badd.6701e780.js index 2ce80a58e..e10d431be 100644 --- a/assets/js/8d81badd.81c8237f.js +++ b/assets/js/8d81badd.6701e780.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom annotations",permalink:"/docs/6.0/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/6.0/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function g(e){let{components:a,...n}=e;return(0,r.yg)(d,(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".'))}g.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"docs",previous:{title:"Custom annotations",permalink:"/docs/6.0/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/6.0/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function g(e){let{components:a,...n}=e;return(0,r.yg)(d,(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".'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/8f7abfe1.7d38c4e5.js b/assets/js/8f7abfe1.0827e6c1.js similarity index 99% rename from assets/js/8f7abfe1.7d38c4e5.js rename to assets/js/8f7abfe1.0827e6c1.js index b8d7bb496..0bd135bda 100644 --- a/assets/js/8f7abfe1.7d38c4e5.js +++ b/assets/js/8f7abfe1.0827e6c1.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.12aee849.js b/assets/js/8f7fa040.19aa9fff.js similarity index 99% rename from assets/js/8f7fa040.12aee849.js rename to assets/js/8f7fa040.19aa9fff.js index 695168e0d..a5c3aa979 100644 --- a/assets/js/8f7fa040.12aee849.js +++ b/assets/js/8f7fa040.19aa9fff.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.686bd959.js b/assets/js/8f951ce3.44fe12e6.js similarity index 98% rename from assets/js/8f951ce3.686bd959.js rename to assets/js/8f951ce3.44fe12e6.js index f033d0fb0..9bd602d34 100644 --- a/assets/js/8f951ce3.686bd959.js +++ b/assets/js/8f951ce3.44fe12e6.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9439],{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))}},88067:(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-4.2/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-4.2/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/4.2/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/prefetch-method.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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)(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([[9439],{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))}},88067:(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-4.2/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-4.2/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/4.2/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.2/prefetch-method.mdx",tags:[],version:"4.2",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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)(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/8f967659.6820bbdd.js b/assets/js/8f967659.2a8b80c0.js similarity index 98% rename from assets/js/8f967659.6820bbdd.js rename to assets/js/8f967659.2a8b80c0.js index ee0cdfeaf..644c98b88 100644 --- a/assets/js/8f967659.6820bbdd.js +++ b/assets/js/8f967659.2a8b80c0.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.e4f1d685.js b/assets/js/9000b231.2d7f009f.js similarity index 98% rename from assets/js/9000b231.e4f1d685.js rename to assets/js/9000b231.2d7f009f.js index 936fb0fd4..9ef3530da 100644 --- a/assets/js/9000b231.e4f1d685.js +++ b/assets/js/9000b231.2d7f009f.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:()=>d});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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"migrating",title:"Release notes",sidebar_label:"Release notes",original_id:"migrating"}},s={},d=[{value:"First stable release of GraphQLite",id:"first-stable-release-of-graphqlite",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},g="wrapper";function u(e){let{components:a,...t}=e;return(0,r.yg)(g,(0,n.A)({},p,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:()=>d});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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"migrating",title:"Release notes",sidebar_label:"Release notes",original_id:"migrating"}},s={},d=[{value:"First stable release of GraphQLite",id:"first-stable-release-of-graphqlite",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},g="wrapper";function u(e){let{components:a,...t}=e;return(0,r.yg)(g,(0,n.A)({},p,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.2450bdcb.js b/assets/js/9073923c.14428e5a.js similarity index 98% rename from assets/js/9073923c.2450bdcb.js rename to assets/js/9073923c.14428e5a.js index d4c7196cf..9c7e80e97 100644 --- a/assets/js/9073923c.2450bdcb.js +++ b/assets/js/9073923c.14428e5a.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.d1dbb559.js b/assets/js/90e0b7fd.db56516a.js similarity index 99% rename from assets/js/90e0b7fd.d1dbb559.js rename to assets/js/90e0b7fd.db56516a.js index dc2ee07a4..d5c769c8c 100644 --- a/assets/js/90e0b7fd.d1dbb559.js +++ b/assets/js/90e0b7fd.db56516a.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 d(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"),"."))}d.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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 d(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"),"."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/9206a32f.5c74cb1b.js b/assets/js/9206a32f.5c4bd34f.js similarity index 99% rename from assets/js/9206a32f.5c74cb1b.js rename to assets/js/9206a32f.5c4bd34f.js index c208fc55f..42275e037 100644 --- a/assets/js/9206a32f.5c74cb1b.js +++ b/assets/js/9206a32f.5c4bd34f.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.fe498c74.js b/assets/js/9279cea7.308af6f9.js similarity index 99% rename from assets/js/9279cea7.fe498c74.js rename to assets/js/9279cea7.308af6f9.js index e506c07cf..8d3531302 100644 --- a/assets/js/9279cea7.fe498c74.js +++ b/assets/js/9279cea7.308af6f9.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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-system/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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-system/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.ba2fa99a.js b/assets/js/947f2c39.ab8670a7.js similarity index 98% rename from assets/js/947f2c39.ba2fa99a.js rename to assets/js/947f2c39.ab8670a7.js index a7efb305e..e0ec8b217 100644 --- a/assets/js/947f2c39.ba2fa99a.js +++ b/assets/js/947f2c39.ab8670a7.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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-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."),(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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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-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."),(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/950394a4.63eb0f08.js b/assets/js/950394a4.ed70f17c.js similarity index 99% rename from assets/js/950394a4.63eb0f08.js rename to assets/js/950394a4.ed70f17c.js index 629091e1a..28eb08b41 100644 --- a/assets/js/950394a4.63eb0f08.js +++ b/assets/js/950394a4.ed70f17c.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/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/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/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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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/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/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/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/95576100.21e23958.js b/assets/js/95576100.6ede392b.js similarity index 99% rename from assets/js/95576100.21e23958.js rename to assets/js/95576100.6ede392b.js index 42ab2cc41..39806f7fd 100644 --- a/assets/js/95576100.21e23958.js +++ b/assets/js/95576100.6ede392b.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.db3a0eb9.js b/assets/js/9664ee55.dfc7699e.js similarity index 99% rename from assets/js/9664ee55.db3a0eb9.js rename to assets/js/9664ee55.dfc7699e.js index 87f906e86..ba9b9b465 100644 --- a/assets/js/9664ee55.db3a0eb9.js +++ b/assets/js/9664ee55.dfc7699e.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.c0200494.js b/assets/js/96877411.4913f2de.js similarity index 99% rename from assets/js/96877411.c0200494.js rename to assets/js/96877411.4913f2de.js index 6552efa45..ffd026768 100644 --- a/assets/js/96877411.c0200494.js +++ b/assets/js/96877411.4913f2de.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/9749ab4a.7572e404.js b/assets/js/9749ab4a.ddfa782f.js similarity index 99% rename from assets/js/9749ab4a.7572e404.js rename to assets/js/9749ab4a.ddfa782f.js index 5d3a36613..bbcf9a8e5 100644 --- a/assets/js/9749ab4a.7572e404.js +++ b/assets/js/9749ab4a.ddfa782f.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.a654a515.js b/assets/js/976f6afc.503f4678.js similarity index 99% rename from assets/js/976f6afc.a654a515.js rename to assets/js/976f6afc.503f4678.js index 5559e53ae..6701c9703 100644 --- a/assets/js/976f6afc.a654a515.js +++ b/assets/js/976f6afc.503f4678.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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.4888f0d5.js b/assets/js/9953ecde.5bddb47b.js similarity index 98% rename from assets/js/9953ecde.4888f0d5.js rename to assets/js/9953ecde.5bddb47b.js index 0851166fa..e7a0125e9 100644 --- a/assets/js/9953ecde.4888f0d5.js +++ b/assets/js/9953ecde.5bddb47b.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/9bd507da.4540c36c.js b/assets/js/9bd507da.e9692c43.js similarity index 98% rename from assets/js/9bd507da.4540c36c.js rename to assets/js/9bd507da.e9692c43.js index 29b68f47e..ec201d702 100644 --- a/assets/js/9bd507da.4540c36c.js +++ b/assets/js/9bd507da.e9692c43.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.15d9be2f.js b/assets/js/9d336ee4.72a6efbc.js similarity index 99% rename from assets/js/9d336ee4.15d9be2f.js rename to assets/js/9d336ee4.72a6efbc.js index 5692768f9..9133ff17b 100644 --- a/assets/js/9d336ee4.15d9be2f.js +++ b/assets/js/9d336ee4.72a6efbc.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ec32e8ef.js b/assets/js/9d9f8394.e9ef5f63.js similarity index 97% rename from assets/js/9d9f8394.ec32e8ef.js rename to assets/js/9d9f8394.e9ef5f63.js index 1c1f69a3c..367a729a4 100644 --- a/assets/js/9d9f8394.ec32e8ef.js +++ b/assets/js/9d9f8394.e9ef5f63.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/next/internals"},next:{title:"Migrating",permalink:"/docs/next/migrating"}},l={},u=[],p={toc:u},c="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},p,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/next/internals"},next:{title:"Migrating",permalink:"/docs/next/migrating"}},l={},u=[],p={toc:u},c="wrapper";function g(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},p,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.1a01299d.js b/assets/js/9f0ecd2e.f5db31e4.js similarity index 98% rename from assets/js/9f0ecd2e.1a01299d.js rename to assets/js/9f0ecd2e.f5db31e4.js index 797a0bfa8..e4c81be52 100644 --- a/assets/js/9f0ecd2e.1a01299d.js +++ b/assets/js/9f0ecd2e.f5db31e4.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.e3ac7f51.js b/assets/js/a0bf4a5f.dcfbd033.js similarity index 98% rename from assets/js/a0bf4a5f.e3ac7f51.js rename to assets/js/a0bf4a5f.dcfbd033.js index 304ac501a..0966fd8a4 100644 --- a/assets/js/a0bf4a5f.e3ac7f51.js +++ b/assets/js/a0bf4a5f.dcfbd033.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.600c339c.js b/assets/js/a13f3cdc.a5356667.js similarity index 99% rename from assets/js/a13f3cdc.600c339c.js rename to assets/js/a13f3cdc.a5356667.js index b160a201a..15961921d 100644 --- a/assets/js/a13f3cdc.600c339c.js +++ b/assets/js/a13f3cdc.a5356667.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[835],{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))}},34394:(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-4.3/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-4.3/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/4.3/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/prefetch-method.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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)(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([[835],{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))}},34394:(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-4.3/prefetch-method",title:"Prefetching records",description:"The problem",source:"@site/versioned_docs/version-4.3/prefetch-method.mdx",sourceDirName:".",slug:"/prefetch-method",permalink:"/docs/4.3/prefetch-method",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.3/prefetch-method.mdx",tags:[],version:"4.3",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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)(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/a16ee953.b2b49229.js b/assets/js/a16ee953.0fbc4b46.js similarity index 99% rename from assets/js/a16ee953.b2b49229.js rename to assets/js/a16ee953.0fbc4b46.js index b8ee2ae51..af5e964a3 100644 --- a/assets/js/a16ee953.b2b49229.js +++ b/assets/js/a16ee953.0fbc4b46.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.5f53de34.js b/assets/js/a1e3d512.07ea288b.js similarity index 99% rename from assets/js/a1e3d512.5f53de34.js rename to assets/js/a1e3d512.07ea288b.js index 1ce6c7f7c..4be8de735 100644 --- a/assets/js/a1e3d512.5f53de34.js +++ b/assets/js/a1e3d512.07ea288b.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9949],{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:()=>T});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 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,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 h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=g(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(!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&&o(m)}),[m]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);o(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:o,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!==o&&(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: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:d,onClick:g},l,{className:(0,i.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":o===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:()=>o,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),l=t(19365);const o={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security",original_id:"fine-grained-security"},s=void 0,u={unversionedId:"fine-grained-security",id:"version-4.1/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-4.1/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/4.1/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/fine-grained-security.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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)(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)(i.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)(i.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)(i.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)(i.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)("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)(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)(i.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)(i.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.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)(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)(i.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)(i.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.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:()=>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:()=>T});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 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,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 h(e){const{defaultValue:a,queryString:t=!1,groupId:n}=e,i=g(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(!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&&o(m)}),[m]);return{selectedValue:l,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:i}))throw new Error(`Can't select invalid tab value=${e}`);o(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:o,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!==o&&(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: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:d,onClick:g},l,{className:(0,i.A)("tabs__item",f.tabItem,l?.className,{"tabs__item--active":o===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:()=>o,metadata:()=>u,toc:()=>c});var n=t(58168),r=(t(96540),t(15680)),i=(t(67443),t(11470)),l=t(19365);const o={id:"fine-grained-security",title:"Fine grained security",sidebar_label:"Fine grained security",original_id:"fine-grained-security"},s=void 0,u={unversionedId:"fine-grained-security",id:"version-4.1/fine-grained-security",title:"Fine grained security",description:"If the @Logged and @Right annotations are not",source:"@site/versioned_docs/version-4.1/fine-grained-security.mdx",sourceDirName:".",slug:"/fine-grained-security",permalink:"/docs/4.1/fine-grained-security",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/fine-grained-security.mdx",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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)(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)(i.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)(i.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)(i.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)(i.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)("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)(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)(i.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)(i.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.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)(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)(i.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)(i.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.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/a23a5b68.250a7b15.js b/assets/js/a23a5b68.35c6cfe4.js similarity index 99% rename from assets/js/a23a5b68.250a7b15.js rename to assets/js/a23a5b68.35c6cfe4.js index ba840e2c1..1919b32a2 100644 --- a/assets/js/a23a5b68.250a7b15.js +++ b/assets/js/a23a5b68.35c6cfe4.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8093],{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:()=>P});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 P(e){const a=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},24483:(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-6.0/laravel-package-advanced",title:"Laravel package: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.0/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/6.0/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/laravel-package-advanced.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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,...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'))))}h.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[8093],{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:()=>P});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 P(e){const a=(0,y.A)();return r.createElement(w,(0,n.A)({key:String(a)},e))}},24483:(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-6.0/laravel-package-advanced",title:"Laravel package: advanced usage",description:"Be advised! This documentation will be removed in a future release. For current and up-to-date Laravel extension specific documentation, please see the Github repository.",source:"@site/versioned_docs/version-6.0/laravel-package-advanced.mdx",sourceDirName:".",slug:"/laravel-package-advanced",permalink:"/docs/6.0/laravel-package-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/laravel-package-advanced.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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,...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'))))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a264d631.3aec4aef.js b/assets/js/a264d631.8c2e8f25.js similarity index 99% rename from assets/js/a264d631.3aec4aef.js rename to assets/js/a264d631.8c2e8f25.js index 53407f75f..2432fea52 100644 --- a/assets/js/a264d631.3aec4aef.js +++ b/assets/js/a264d631.8c2e8f25.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),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 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:()=>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-5.0/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-5.0/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/5.0/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/error-handling.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"version-5.0/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/5.0/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/5.0/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function 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),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 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:()=>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-5.0/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-5.0/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/5.0/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-5.0/error-handling.mdx",tags:[],version:"5.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"version-5.0/docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/5.0/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/5.0/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function 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.1e3d8131.js b/assets/js/a27ea030.421025a3.js similarity index 98% rename from assets/js/a27ea030.1e3d8131.js rename to assets/js/a27ea030.421025a3.js index 28be8ad84..d869520a5 100644 --- a/assets/js/a27ea030.1e3d8131.js +++ b/assets/js/a27ea030.421025a3.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[68],{95007:(e,t,r)=>{r.r(t),r.d(t,{assets:()=>d,contentTitle:()=>o,default:()=>h,frontMatter:()=>n,metadata:()=>u,toc:()=>l});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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},d={},l=[{value:"The problem",id:"the-problem",level:2},{value:"Apollo APQ",id:"apollo-apq",level:2},{value:"Setup",id:"setup",level:2}],p={toc:l},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:()=>d,contentTitle:()=>o,default:()=>h,frontMatter:()=>n,metadata:()=>u,toc:()=>l});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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},d={},l=[{value:"The problem",id:"the-problem",level:2},{value:"Apollo APQ",id:"apollo-apq",level:2},{value:"Setup",id:"setup",level:2}],p={toc:l},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.f4c630d8.js b/assets/js/a27f6be0.93950472.js similarity index 98% rename from assets/js/a27f6be0.f4c630d8.js rename to assets/js/a27f6be0.93950472.js index 4471d6802..8eb6032e6 100644 --- a/assets/js/a27f6be0.f4c630d8.js +++ b/assets/js/a27f6be0.93950472.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.1711f5a4.js b/assets/js/a28aff23.d95ba250.js similarity index 99% rename from assets/js/a28aff23.1711f5a4.js rename to assets/js/a28aff23.d95ba250.js index a9fbe6f12..bfbac4cbf 100644 --- a/assets/js/a28aff23.1711f5a4.js +++ b/assets/js/a28aff23.d95ba250.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 p(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 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,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=p(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}))),[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 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),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_)(),p=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},h=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 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:h,onClick:p},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"docs",previous:{title:"User input validation",permalink:"/docs/6.0/validation"},next:{title:"Fine grained security",permalink:"/docs/6.0/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(h,(0,a.A)({},p,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 p(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 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,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=p(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}))),[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 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),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_)(),p=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},h=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 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:h,onClick:p},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"docs",previous:{title:"User input validation",permalink:"/docs/6.0/validation"},next:{title:"Fine grained security",permalink:"/docs/6.0/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(h,(0,a.A)({},p,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.8e3e1cb6.js b/assets/js/a2d3d8d2.6dcfb1a2.js similarity index 99% rename from assets/js/a2d3d8d2.8e3e1cb6.js rename to assets/js/a2d3d8d2.6dcfb1a2.js index 37308575e..1fb38cffe 100644 --- a/assets/js/a2d3d8d2.8e3e1cb6.js +++ b/assets/js/a2d3d8d2.6dcfb1a2.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.50645db0.js b/assets/js/a30fd8ca.615ed318.js similarity index 99% rename from assets/js/a30fd8ca.50645db0.js rename to assets/js/a30fd8ca.615ed318.js index 909564603..577140aaa 100644 --- a/assets/js/a30fd8ca.50645db0.js +++ b/assets/js/a30fd8ca.615ed318.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ee5d6717.js b/assets/js/a320b509.7ab18136.js similarity index 98% rename from assets/js/a320b509.ee5d6717.js rename to assets/js/a320b509.7ab18136.js index 7b36fc5c6..5c1feb2f4 100644 --- a/assets/js/a320b509.ee5d6717.js +++ b/assets/js/a320b509.7ab18136.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.e6f82b19.js b/assets/js/a3a193a6.66147a15.js similarity index 98% rename from assets/js/a3a193a6.e6f82b19.js rename to assets/js/a3a193a6.66147a15.js index d49dfb310..7ea624b24 100644 --- a/assets/js/a3a193a6.e6f82b19.js +++ b/assets/js/a3a193a6.66147a15.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:()=>u,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning",original_id:"semver"},sidebar:"version-4.0/docs",previous:{title:"Annotations reference",permalink:"/docs/4.0/annotations_reference"},next:{title:"Changelog",permalink:"/docs/4.0/changelog"}},l={},p=[],m={toc:p},d="wrapper";function u(e){let{components:a,...t}=e;return(0,n.yg)(d,(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."))}u.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:()=>u,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"semver",title:"Our backward compatibility promise",sidebar_label:"Semantic versioning",original_id:"semver"},sidebar:"version-4.0/docs",previous:{title:"Annotations reference",permalink:"/docs/4.0/annotations_reference"},next:{title:"Changelog",permalink:"/docs/4.0/changelog"}},l={},p=[],m={toc:p},d="wrapper";function u(e){let{components:a,...t}=e;return(0,n.yg)(d,(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."))}u.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a55b0daf.8b9c7c4f.js b/assets/js/a55b0daf.d5861c2c.js similarity index 99% rename from assets/js/a55b0daf.8b9c7c4f.js rename to assets/js/a55b0daf.d5861c2c.js index 3ed8d744d..1eef07d8e 100644 --- a/assets/js/a55b0daf.8b9c7c4f.js +++ b/assets/js/a55b0daf.d5861c2c.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ea36bda7.js b/assets/js/a9125b44.2e25c318.js similarity index 99% rename from assets/js/a9125b44.ea36bda7.js rename to assets/js/a9125b44.2e25c318.js index aa2b852eb..0badef420 100644 --- a/assets/js/a9125b44.ea36bda7.js +++ b/assets/js/a9125b44.2e25c318.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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/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.2f51963a.js b/assets/js/a91c1a62.151c5c44.js similarity index 97% rename from assets/js/a91c1a62.2f51963a.js rename to assets/js/a91c1a62.151c5c44.js index 121de81aa..4a4640c8f 100644 --- a/assets/js/a91c1a62.2f51963a.js +++ b/assets/js/a91c1a62.151c5c44.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:()=>d,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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/internals"},next:{title:"Migrating",permalink:"/docs/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},p,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."))}d.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:()=>d,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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/internals"},next:{title:"Migrating",permalink:"/docs/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},p,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."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/a95c9e82.74ac082a.js b/assets/js/a95c9e82.85a1f0cf.js similarity index 99% rename from assets/js/a95c9e82.74ac082a.js rename to assets/js/a95c9e82.85a1f0cf.js index 6597ef79f..649200598 100644 --- a/assets/js/a95c9e82.74ac082a.js +++ b/assets/js/a95c9e82.85a1f0cf.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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.760f22fa.js b/assets/js/a99e9943.6c8a6d61.js similarity index 98% rename from assets/js/a99e9943.760f22fa.js rename to assets/js/a99e9943.6c8a6d61.js index 28a514cb4..2601999c0 100644 --- a/assets/js/a99e9943.760f22fa.js +++ b/assets/js/a99e9943.6c8a6d61.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.fa1f1757.js b/assets/js/a9bc4f03.b4a3dfa1.js similarity index 99% rename from assets/js/a9bc4f03.fa1f1757.js rename to assets/js/a9bc4f03.b4a3dfa1.js index 5476c79f0..443ec021b 100644 --- a/assets/js/a9bc4f03.fa1f1757.js +++ b/assets/js/a9bc4f03.b4a3dfa1.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.67b98c1e.js b/assets/js/aa52484c.74012053.js similarity index 98% rename from assets/js/aa52484c.67b98c1e.js rename to assets/js/aa52484c.74012053.js index 0f56fcc0a..7726c00eb 100644 --- a/assets/js/aa52484c.67b98c1e.js +++ b/assets/js/aa52484c.74012053.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.8403baf7.js b/assets/js/aa5b6080.5bf1d237.js similarity index 99% rename from assets/js/aa5b6080.8403baf7.js rename to assets/js/aa5b6080.5bf1d237.js index 3a78537c8..07a8f9fc7 100644 --- a/assets/js/aa5b6080.8403baf7.js +++ b/assets/js/aa5b6080.5bf1d237.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.60b0926d.js b/assets/js/aa675676.61394c21.js similarity index 99% rename from assets/js/aa675676.60b0926d.js rename to assets/js/aa675676.61394c21.js index 7fcbc6f45..c95cbebd7 100644 --- a/assets/js/aa675676.60b0926d.js +++ b/assets/js/aa675676.61394c21.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.035001c1.js b/assets/js/aba5bf07.2edcb8ab.js similarity index 99% rename from assets/js/aba5bf07.035001c1.js rename to assets/js/aba5bf07.2edcb8ab.js index d42e54cfc..a616e2637 100644 --- a/assets/js/aba5bf07.035001c1.js +++ b/assets/js/aba5bf07.2edcb8ab.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},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/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},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/authentication-authorization"},"Authentication and authorization page"),", or any annotation this is actually a ",(0,o.yg)("a",{parentName:"p",href:"/docs/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.efbab152.js b/assets/js/ac8293fa.5590a3a2.js similarity index 99% rename from assets/js/ac8293fa.efbab152.js rename to assets/js/ac8293fa.5590a3a2.js index 5d9004a7e..00be59ed7 100644 --- a/assets/js/ac8293fa.efbab152.js +++ b/assets/js/ac8293fa.5590a3a2.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 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 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=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=g({queryString:a,groupId:n}),[d,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??d;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:d}=(0,u.a_)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.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:p},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:()=>d});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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/6.0/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(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)(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 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 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=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=g({queryString:a,groupId:n}),[d,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??d;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:d}=(0,u.a_)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.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:p},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:()=>d});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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/6.0/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(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)(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.212ed806.js b/assets/js/acbaac14.df94e672.js similarity index 99% rename from assets/js/acbaac14.212ed806.js rename to assets/js/acbaac14.df94e672.js index 6e805e0a3..03f602b9d 100644 --- a/assets/js/acbaac14.212ed806.js +++ b/assets/js/acbaac14.df94e672.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.5aab8eff.js b/assets/js/ae0a12ed.3ea7f2e0.js similarity index 99% rename from assets/js/ae0a12ed.5aab8eff.js rename to assets/js/ae0a12ed.3ea7f2e0.js index 76af5843a..33d609f98 100644 --- a/assets/js/ae0a12ed.5aab8eff.js +++ b/assets/js/ae0a12ed.3ea7f2e0.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.9e1d2104.js b/assets/js/aebf35b6.2c35a4e2.js similarity index 99% rename from assets/js/aebf35b6.9e1d2104.js rename to assets/js/aebf35b6.2c35a4e2.js index acbdb715f..739510a9c 100644 --- a/assets/js/aebf35b6.9e1d2104.js +++ b/assets/js/aebf35b6.2c35a4e2.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.1e48dcce.js b/assets/js/b06c439f.a328d225.js similarity index 99% rename from assets/js/b06c439f.1e48dcce.js rename to assets/js/b06c439f.a328d225.js index eef78d0e3..b462b3b81 100644 --- a/assets/js/b06c439f.1e48dcce.js +++ b/assets/js/b06c439f.a328d225.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.6e1fd2a9.js b/assets/js/b0ed7ea5.e78cbc24.js similarity index 99% rename from assets/js/b0ed7ea5.6e1fd2a9.js rename to assets/js/b0ed7ea5.e78cbc24.js index c8d2781cf..58059d89d 100644 --- a/assets/js/b0ed7ea5.6e1fd2a9.js +++ b/assets/js/b0ed7ea5.e78cbc24.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.abdaf47c.js b/assets/js/b103c05a.3f1db171.js similarity index 99% rename from assets/js/b103c05a.abdaf47c.js rename to assets/js/b103c05a.3f1db171.js index 81261975e..f514ce778 100644 --- a/assets/js/b103c05a.abdaf47c.js +++ b/assets/js/b103c05a.3f1db171.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.df74297c.js b/assets/js/b26a5b84.70df5a5a.js similarity index 99% rename from assets/js/b26a5b84.df74297c.js rename to assets/js/b26a5b84.70df5a5a.js index ca1dfe5f9..655c088b7 100644 --- a/assets/js/b26a5b84.df74297c.js +++ b/assets/js/b26a5b84.70df5a5a.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.8b170ae8.js b/assets/js/b2d9540a.94cb79db.js similarity index 99% rename from assets/js/b2d9540a.8b170ae8.js rename to assets/js/b2d9540a.94cb79db.js index 0f8a7eab8..4cba3429f 100644 --- a/assets/js/b2d9540a.8b170ae8.js +++ b/assets/js/b2d9540a.94cb79db.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[1084],{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))}},90837:(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-6.0/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-6.0/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/6.0/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/validation.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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: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/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,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))}},90837:(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-6.0/validation",title:"Validation",description:"GraphQLite does not handle user input validation by itself. It is out of its scope.",source:"@site/versioned_docs/version-6.0/validation.mdx",sourceDirName:".",slug:"/validation",permalink:"/docs/6.0/validation",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/validation.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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: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/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.f62c70b4.js b/assets/js/b35d1284.29c39c4b.js similarity index 98% rename from assets/js/b35d1284.f62c70b4.js rename to assets/js/b35d1284.29c39c4b.js index 67eca0740..baa1f7b65 100644 --- a/assets/js/b35d1284.f62c70b4.js +++ b/assets/js/b35d1284.29c39c4b.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ded65cc0.js b/assets/js/b370b50c.020852bb.js similarity index 99% rename from assets/js/b370b50c.ded65cc0.js rename to assets/js/b370b50c.020852bb.js index f69155833..803a6818a 100644 --- a/assets/js/b370b50c.ded65cc0.js +++ b/assets/js/b370b50c.020852bb.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:()=>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 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 A(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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:()=>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 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 A(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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.3e26017e.js b/assets/js/b42f5805.c207b0b2.js similarity index 99% rename from assets/js/b42f5805.3e26017e.js rename to assets/js/b42f5805.c207b0b2.js index 3602a2436..e7be64578 100644 --- a/assets/js/b42f5805.3e26017e.js +++ b/assets/js/b42f5805.c207b0b2.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.0a64f0ff.js b/assets/js/b4657038.78fb71e5.js similarity index 98% rename from assets/js/b4657038.0a64f0ff.js rename to assets/js/b4657038.78fb71e5.js index f4a9ff499..9d8d2f31b 100644 --- a/assets/js/b4657038.0a64f0ff.js +++ b/assets/js/b4657038.78fb71e5.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:()=>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"},r=void 0,s={unversionedId:"doctrine-annotations-attributes",id:"version-3.0/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-3.0/doctrine_annotations_attributes.md",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/3.0/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/doctrine_annotations_attributes.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"}},l={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],u={toc:p},d="wrapper";function c(t){let{components:e,...n}=t;return(0,i.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/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")))}c.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:()=>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"},r=void 0,s={unversionedId:"doctrine-annotations-attributes",id:"version-3.0/doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",description:"GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).",source:"@site/versioned_docs/version-3.0/doctrine_annotations_attributes.md",sourceDirName:".",slug:"/doctrine-annotations-attributes",permalink:"/docs/3.0/doctrine-annotations-attributes",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/doctrine_annotations_attributes.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"doctrine-annotations-attributes",title:"Doctrine annotations VS PHP8 attributes",sidebar_label:"Annotations VS Attributes"}},l={},p=[{value:"Doctrine annotations",id:"doctrine-annotations",level:2},{value:"PHP 8 attributes",id:"php-8-attributes",level:2}],u={toc:p},d="wrapper";function c(t){let{components:e,...n}=t;return(0,i.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/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")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b4aea2ce.b8c1c91c.js b/assets/js/b4aea2ce.e042c4be.js similarity index 98% rename from assets/js/b4aea2ce.b8c1c91c.js rename to assets/js/b4aea2ce.e042c4be.js index c321d1caf..93739c772 100644 --- a/assets/js/b4aea2ce.b8c1c91c.js +++ b/assets/js/b4aea2ce.e042c4be.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.06097821.js b/assets/js/b5d0ac54.0c090973.js similarity index 99% rename from assets/js/b5d0ac54.06097821.js rename to assets/js/b5d0ac54.0c090973.js index 473a93d22..1996e1389 100644 --- a/assets/js/b5d0ac54.06097821.js +++ b/assets/js/b5d0ac54.0c090973.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.fb4df112.js b/assets/js/b5d32d98.f3319d03.js similarity index 98% rename from assets/js/b5d32d98.fb4df112.js rename to assets/js/b5d32d98.f3319d03.js index 36b23534b..1c9004cdf 100644 --- a/assets/js/b5d32d98.fb4df112.js +++ b/assets/js/b5d32d98.f3319d03.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.c33ad6bb.js b/assets/js/b6722b03.706f9763.js similarity index 99% rename from assets/js/b6722b03.c33ad6bb.js rename to assets/js/b6722b03.706f9763.js index 9c3a0a1cd..5cf269227 100644 --- a/assets/js/b6722b03.c33ad6bb.js +++ b/assets/js/b6722b03.706f9763.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/",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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/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/",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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"docs",next:{title:"Getting Started",permalink:"/docs/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/b6a6a31f.f3cfb108.js b/assets/js/b6a6a31f.f3a4b1ab.js similarity index 98% rename from assets/js/b6a6a31f.f3cfb108.js rename to assets/js/b6a6a31f.f3a4b1ab.js index 5875ed558..8ed155990 100644 --- a/assets/js/b6a6a31f.f3cfb108.js +++ b/assets/js/b6a6a31f.f3a4b1ab.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.f1dfeb88.js b/assets/js/b7442939.6e0e3185.js similarity index 99% rename from assets/js/b7442939.f1dfeb88.js rename to assets/js/b7442939.6e0e3185.js index 1d65a9a2f..6f7bce6c7 100644 --- a/assets/js/b7442939.f1dfeb88.js +++ b/assets/js/b7442939.6e0e3185.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"version-4.3/docs",previous:{title:"Custom annotations",permalink:"/docs/4.3/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/4.3/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function g(e){let{components:a,...n}=e;return(0,r.yg)(d,(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".'))}g.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"version-4.3/docs",previous:{title:"Custom annotations",permalink:"/docs/4.3/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/4.3/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function g(e){let{components:a,...n}=e;return(0,r.yg)(d,(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".'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b8487569.8aa4dd2e.js b/assets/js/b8487569.34de94db.js similarity index 99% rename from assets/js/b8487569.8aa4dd2e.js rename to assets/js/b8487569.34de94db.js index d9dae758f..92e325a31 100644 --- a/assets/js/b8487569.8aa4dd2e.js +++ b/assets/js/b8487569.34de94db.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.989eaf9b.js b/assets/js/b94a1068.70ece279.js similarity index 99% rename from assets/js/b94a1068.989eaf9b.js rename to assets/js/b94a1068.70ece279.js index be2da75ad..469641084 100644 --- a/assets/js/b94a1068.989eaf9b.js +++ b/assets/js/b94a1068.70ece279.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.a0a8a034.js b/assets/js/b9d6d6e5.ed929d1d.js similarity index 98% rename from assets/js/b9d6d6e5.a0a8a034.js rename to assets/js/b9d6d6e5.ed929d1d.js index a761d7fc4..695f42ff8 100644 --- a/assets/js/b9d6d6e5.a0a8a034.js +++ b/assets/js/b9d6d6e5.ed929d1d.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.54ec31ba.js b/assets/js/b9ea999a.a642f64a.js similarity index 99% rename from assets/js/b9ea999a.54ec31ba.js rename to assets/js/b9ea999a.a642f64a.js index 776c8e6c7..b075ae1ce 100644 --- a/assets/js/b9ea999a.54ec31ba.js +++ b/assets/js/b9ea999a.a642f64a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2830],{16295:(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",original_id:"annotations_reference"},i=void 0,o={unversionedId:"annotations_reference",id:"version-4.1/annotations_reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/versioned_docs/version-4.1/annotations_reference.md",sourceDirName:".",slug:"/annotations_reference",permalink:"/docs/4.1/annotations_reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/annotations_reference.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"annotations_reference",title:"Annotations reference",sidebar_label:"Annotations reference",original_id:"annotations_reference"},sidebar:"version-4.1/docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/4.1/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/4.1/semver"}},p={},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:"@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.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:()=>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",original_id:"annotations_reference"},i=void 0,o={unversionedId:"annotations_reference",id:"version-4.1/annotations_reference",title:"Annotations reference",description:"Note: all annotations are available both in a Doctrine annotation format (@Query) and in PHP 8 attribute format (#[Query]).",source:"@site/versioned_docs/version-4.1/annotations_reference.md",sourceDirName:".",slug:"/annotations_reference",permalink:"/docs/4.1/annotations_reference",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/annotations_reference.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"annotations_reference",title:"Annotations reference",sidebar_label:"Annotations reference",original_id:"annotations_reference"},sidebar:"version-4.1/docs",previous:{title:"Annotations VS Attributes",permalink:"/docs/4.1/doctrine-annotations-attributes"},next:{title:"Semantic versioning",permalink:"/docs/4.1/semver"}},p={},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:"@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.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.5b47d0d7.js b/assets/js/ba7653ad.bbc1d3a3.js similarity index 99% rename from assets/js/ba7653ad.5b47d0d7.js rename to assets/js/ba7653ad.bbc1d3a3.js index 45b04a1bf..3271c8713 100644 --- a/assets/js/ba7653ad.5b47d0d7.js +++ b/assets/js/ba7653ad.bbc1d3a3.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.e0206554.js b/assets/js/bb5ef1b7.2c1da688.js similarity index 99% rename from assets/js/bb5ef1b7.e0206554.js rename to assets/js/bb5ef1b7.2c1da688.js index 22a8fc95a..3713f74e4 100644 --- a/assets/js/bb5ef1b7.e0206554.js +++ b/assets/js/bb5ef1b7.2c1da688.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.5f6f8397.js b/assets/js/bb9fe7c3.fe26e692.js similarity index 99% rename from assets/js/bb9fe7c3.5f6f8397.js rename to assets/js/bb9fe7c3.fe26e692.js index 30288dad8..745f16a29 100644 --- a/assets/js/bb9fe7c3.5f6f8397.js +++ b/assets/js/bb9fe7c3.fe26e692.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.d7d64164.js b/assets/js/bcb6471f.e5fedff8.js similarity index 99% rename from assets/js/bcb6471f.d7d64164.js rename to assets/js/bcb6471f.e5fedff8.js index 1dc21ec2a..553be2c0f 100644 --- a/assets/js/bcb6471f.d7d64164.js +++ b/assets/js/bcb6471f.e5fedff8.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3196],{77375:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>s});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"},o=void 0,i={unversionedId:"symfony-bundle",id:"version-4.1/symfony-bundle",title:"Getting started with Symfony",description:"The GraphQLite bundle is compatible with Symfony 4.x and Symfony 5.x.",source:"@site/versioned_docs/version-4.1/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/4.1/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/symfony-bundle.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 d(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},y,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")," 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"},"{t.r(n),t.d(n,{assets:()=>p,contentTitle:()=>o,default:()=>d,frontMatter:()=>l,metadata:()=>i,toc:()=>s});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"},o=void 0,i={unversionedId:"symfony-bundle",id:"version-4.1/symfony-bundle",title:"Getting started with Symfony",description:"The GraphQLite bundle is compatible with Symfony 4.x and Symfony 5.x.",source:"@site/versioned_docs/version-4.1/symfony-bundle.md",sourceDirName:".",slug:"/symfony-bundle",permalink:"/docs/4.1/symfony-bundle",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-4.1/symfony-bundle.md",tags:[],version:"4.1",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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 d(e){let{components:n,...t}=e;return(0,r.yg)(g,(0,a.A)({},y,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")," 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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.00d5dde8.js b/assets/js/bd2c4a98.96e2d1cb.js similarity index 99% rename from assets/js/bd2c4a98.00d5dde8.js rename to assets/js/bd2c4a98.96e2d1cb.js index 63f0e1b6b..785305cf9 100644 --- a/assets/js/bd2c4a98.00d5dde8.js +++ b/assets/js/bd2c4a98.96e2d1cb.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.3356cab1.js b/assets/js/bda39da3.42af0747.js similarity index 98% rename from assets/js/bda39da3.3356cab1.js rename to assets/js/bda39da3.42af0747.js index d230b9608..228f6ba2a 100644 --- a/assets/js/bda39da3.3356cab1.js +++ b/assets/js/bda39da3.42af0747.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.d803a9da.js b/assets/js/bdb33130.60d5e579.js similarity index 99% rename from assets/js/bdb33130.d803a9da.js rename to assets/js/bdb33130.60d5e579.js index bccfd05b4..4f4f6a3ea 100644 --- a/assets/js/bdb33130.d803a9da.js +++ b/assets/js/bdb33130.60d5e579.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 d(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")))}d.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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 d(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")))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/be1f0304.730884bb.js b/assets/js/be1f0304.e6b63afc.js similarity index 99% rename from assets/js/be1f0304.730884bb.js rename to assets/js/be1f0304.e6b63afc.js index e48191015..6896ea592 100644 --- a/assets/js/be1f0304.730884bb.js +++ b/assets/js/be1f0304.e6b63afc.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.30f90fdb.js b/assets/js/beccb025.0cf1609c.js similarity index 98% rename from assets/js/beccb025.30f90fdb.js rename to assets/js/beccb025.0cf1609c.js index 6688e726c..dbf25663b 100644 --- a/assets/js/beccb025.30f90fdb.js +++ b/assets/js/beccb025.0cf1609c.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.2a3df866.js b/assets/js/bf2a5963.8d2652ff.js similarity index 99% rename from assets/js/bf2a5963.2a3df866.js rename to assets/js/bf2a5963.8d2652ff.js index 8631b0343..8685ef45a 100644 --- a/assets/js/bf2a5963.2a3df866.js +++ b/assets/js/bf2a5963.8d2652ff.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/c007fb39.7a129435.js b/assets/js/c007fb39.78d67697.js similarity index 99% rename from assets/js/c007fb39.7a129435.js rename to assets/js/c007fb39.78d67697.js index 92bcda2d2..236179247 100644 --- a/assets/js/c007fb39.7a129435.js +++ b/assets/js/c007fb39.78d67697.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),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 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:()=>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-6.0/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-6.0/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/6.0/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/error-handling.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/6.0/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/6.0/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function 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),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 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:()=>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-6.0/error-handling",title:"Error handling",description:'In GraphQL, when an error occurs, the server must add an "error" entry in the response.',source:"@site/versioned_docs/version-6.0/error-handling.mdx",sourceDirName:".",slug:"/error-handling",permalink:"/docs/6.0/error-handling",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/error-handling.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"error-handling",title:"Error handling",sidebar_label:"Error handling"},sidebar:"docs",previous:{title:"Inheritance and interfaces",permalink:"/docs/6.0/inheritance-interfaces"},next:{title:"User input validation",permalink:"/docs/6.0/validation"}},c={},p=[{value:"HTTP response code",id:"http-response-code",level:2},{value:"Customizing the category",id:"customizing-the-category",level:2},{value:"Customizing the extensions section",id:"customizing-the-extensions-section",level:2},{value:"Writing your own exceptions",id:"writing-your-own-exceptions",level:2},{value:"Many errors for one exception",id:"many-errors-for-one-exception",level:2},{value:"Webonyx exceptions",id:"webonyx-exceptions",level:2},{value:"Behaviour of exceptions that do not implement ClientAware",id:"behaviour-of-exceptions-that-do-not-implement-clientaware",level:2}],h={toc:p},d="wrapper";function 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.d13d334d.js b/assets/js/c0fa6485.5373e105.js similarity index 98% rename from assets/js/c0fa6485.d13d334d.js rename to assets/js/c0fa6485.5373e105.js index c7cc90ed8..772149313 100644 --- a/assets/js/c0fa6485.d13d334d.js +++ b/assets/js/c0fa6485.5373e105.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/c10d4a63.f2de6ddf.js b/assets/js/c10d4a63.b22f5985.js similarity index 99% rename from assets/js/c10d4a63.f2de6ddf.js rename to assets/js/c10d4a63.b22f5985.js index 66eb06597..e33f7ca52 100644 --- a/assets/js/c10d4a63.f2de6ddf.js +++ b/assets/js/c10d4a63.b22f5985.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),p=a(57485),o=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,o.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,p.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}))),[p,o]=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=p??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),o(e),h(e)}),[o,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:p,tabValues:o}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.a_)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=o[a].value;n!==i&&(d(t),p(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)},o.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))}},71592:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>p,default:()=>m,frontMatter:()=>i,metadata:()=>o,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"},p=void 0,o={unversionedId:"multiple-output-types",id:"version-6.0/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.0/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/6.0/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/multiple-output-types.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"docs",previous:{title:"Extending an input type",permalink:"/docs/6.0/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/6.0/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},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/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),p=a(57485),o=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,o.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,p.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}))),[p,o]=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=p??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),o(e),h(e)}),[o,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:p,tabValues:o}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.a_)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=o[a].value;n!==i&&(d(t),p(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)},o.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))}},71592:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>p,default:()=>m,frontMatter:()=>i,metadata:()=>o,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"},p=void 0,o={unversionedId:"multiple-output-types",id:"version-6.0/multiple-output-types",title:"Mapping multiple output types for the same class",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-6.0/multiple-output-types.mdx",sourceDirName:".",slug:"/multiple-output-types",permalink:"/docs/6.0/multiple-output-types",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-6.0/multiple-output-types.mdx",tags:[],version:"6.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"multiple-output-types",title:"Mapping multiple output types for the same class",sidebar_label:"Class with multiple output types"},sidebar:"docs",previous:{title:"Extending an input type",permalink:"/docs/6.0/extend-input-type"},next:{title:"Symfony specific features",permalink:"/docs/6.0/symfony-bundle-advanced"}},s={},d=[{value:"Example",id:"example",level:2},{value:"Extending a non-default type",id:"extending-a-non-default-type",level:2}],c={toc:d},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/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.5c47ead6.js b/assets/js/c1fe0282.e663460d.js similarity index 99% rename from assets/js/c1fe0282.5c47ead6.js rename to assets/js/c1fe0282.e663460d.js index 4b61a6f2f..808272f1a 100644 --- a/assets/js/c1fe0282.5c47ead6.js +++ b/assets/js/c1fe0282.e663460d.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.738c0c33.js b/assets/js/c275698c.fc512c41.js similarity index 99% rename from assets/js/c275698c.738c0c33.js rename to assets/js/c275698c.fc512c41.js index 8fdb07165..e49fdf2e3 100644 --- a/assets/js/c275698c.738c0c33.js +++ b/assets/js/c275698c.fc512c41.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.e61d729d.js b/assets/js/c329487f.d022b7c1.js similarity index 99% rename from assets/js/c329487f.e61d729d.js rename to assets/js/c329487f.d022b7c1.js index 384379835..d63b305c7 100644 --- a/assets/js/c329487f.e61d729d.js +++ b/assets/js/c329487f.d022b7c1.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/c3701568.24a3bd1a.js b/assets/js/c3701568.5cb9c150.js similarity index 98% rename from assets/js/c3701568.24a3bd1a.js rename to assets/js/c3701568.5cb9c150.js index ec738e930..f69225a41 100644 --- a/assets/js/c3701568.24a3bd1a.js +++ b/assets/js/c3701568.5cb9c150.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:()=>u});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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services",original_id:"autowiring"},sidebar:"version-4.0/docs",previous:{title:"Type mapping",permalink:"/docs/4.0/type_mapping"},next:{title:"Extending a type",permalink:"/docs/4.0/extend_type"}},l={},u=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],c={toc:u},d="wrapper";function p(e){let{components:t,...i}=e;return(0,a.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")," 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:()=>u});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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"autowiring",title:"Autowiring services",sidebar_label:"Autowiring services",original_id:"autowiring"},sidebar:"version-4.0/docs",previous:{title:"Type mapping",permalink:"/docs/4.0/type_mapping"},next:{title:"Extending a type",permalink:"/docs/4.0/extend_type"}},l={},u=[{value:"Sample",id:"sample",level:2},{value:"Best practices",id:"best-practices",level:2},{value:"Fetching a service by name (discouraged!)",id:"fetching-a-service-by-name-discouraged",level:2},{value:"Alternative solution",id:"alternative-solution",level:2}],c={toc:u},d="wrapper";function p(e){let{components:t,...i}=e;return(0,a.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")," 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.e63e72c1.js b/assets/js/c4d37b36.ebe7ba67.js similarity index 99% rename from assets/js/c4d37b36.e63e72c1.js rename to assets/js/c4d37b36.ebe7ba67.js index 8052971b5..5dc6f633e 100644 --- a/assets/js/c4d37b36.e63e72c1.js +++ b/assets/js/c4d37b36.ebe7ba67.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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},d="wrapper";function g(e){let{components:a,...n}=e;return(0,r.yg)(d,(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".'))}g.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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},d="wrapper";function g(e){let{components:a,...n}=e;return(0,r.yg)(d,(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".'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/c5fa393d.317dd843.js b/assets/js/c5fa393d.c9ae6aa6.js similarity index 98% rename from assets/js/c5fa393d.317dd843.js rename to assets/js/c5fa393d.c9ae6aa6.js index 40bea9a10..4cb97cafc 100644 --- a/assets/js/c5fa393d.317dd843.js +++ b/assets/js/c5fa393d.c9ae6aa6.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.24f7f4ac.js b/assets/js/c69dda99.7bed8d0f.js similarity index 99% rename from assets/js/c69dda99.24f7f4ac.js rename to assets/js/c69dda99.7bed8d0f.js index 896b6289d..0b2476f07 100644 --- a/assets/js/c69dda99.24f7f4ac.js +++ b/assets/js/c69dda99.7bed8d0f.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 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 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=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=g({queryString:a,groupId:n}),[d,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??d;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:d}=(0,u.a_)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.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:p},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:()=>d});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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"version-4.2/docs",next:{title:"Getting Started",permalink:"/docs/4.2/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(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)(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 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 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=p(e),[u,o]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:a}=e;if(0===a.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:a}))throw new Error(`Docusaurus error: The has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${a.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const n=a.find((e=>e.default))??a[0];if(!n)throw new Error("Unexpected error: 0 tabValues");return n.value}({defaultValue:t,tabValues:l}))),[s,i]=g({queryString:a,groupId:n}),[d,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??d;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:d}=(0,u.a_)(),p=e=>{const t=e.currentTarget,a=c.indexOf(t),n=i[a].value;n!==o&&(d(t),s(n))},m=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const a=c.indexOf(e.currentTarget)+1;t=c[a]??c[0];break}case"ArrowLeft":{const a=c.indexOf(e.currentTarget)-1;t=c[a]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,l.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:p},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:()=>d});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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"index",title:"GraphQLite",slug:"/",sidebar_label:"GraphQLite"},sidebar:"version-4.2/docs",next:{title:"Getting Started",permalink:"/docs/4.2/getting-started"}},c={},d=[{value:"Features",id:"features",level:2},{value:"Basic example",id:"basic-example",level:2}],p={toc:d},m="wrapper";function g(e){let{components:t,...a}=e;return(0,r.yg)(m,(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)(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/c7a4caa1.437fdf09.js b/assets/js/c7a4caa1.d204f912.js similarity index 98% rename from assets/js/c7a4caa1.437fdf09.js rename to assets/js/c7a4caa1.d204f912.js index 588107f71..b15cddbe9 100644 --- a/assets/js/c7a4caa1.437fdf09.js +++ b/assets/js/c7a4caa1.d204f912.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.62df2119.js b/assets/js/c7e7ae18.8214a40d.js similarity index 99% rename from assets/js/c7e7ae18.62df2119.js rename to assets/js/c7e7ae18.8214a40d.js index 68d00d699..d3660a9de 100644 --- a/assets/js/c7e7ae18.62df2119.js +++ b/assets/js/c7e7ae18.8214a40d.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.e0efc303.js b/assets/js/c8bdc4df.390ff8eb.js similarity index 98% rename from assets/js/c8bdc4df.e0efc303.js rename to assets/js/c8bdc4df.390ff8eb.js index 471f89e38..0c1c5deaf 100644 --- a/assets/js/c8bdc4df.e0efc303.js +++ b/assets/js/c8bdc4df.390ff8eb.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[5316],{82513:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>l,default:()=>h,frontMatter:()=>r,metadata:()=>n,toc:()=>s});var o=t(58168),i=(t(96540),t(15680));t(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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},sidebar:"version-4.0/docs",previous:{title:"Prefetching records",permalink:"/docs/4.0/prefetch-method"},next:{title:"Pagination",permalink:"/docs/4.0/pagination"}},p={},s=[{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:2},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:2},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:2},{value:"Usage",id:"usage",level:2}],u={toc:s},d="wrapper";function h(e){let{components: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([[5316],{82513:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>l,default:()=>h,frontMatter:()=>r,metadata:()=>n,toc:()=>s});var o=t(58168),i=(t(96540),t(15680));t(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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"file-uploads",title:"File uploads",sidebar_label:"File uploads",original_id:"file-uploads"},sidebar:"version-4.0/docs",previous:{title:"Prefetching records",permalink:"/docs/4.0/prefetch-method"},next:{title:"Pagination",permalink:"/docs/4.0/pagination"}},p={},s=[{value:"If you are using the Symfony bundle",id:"if-you-are-using-the-symfony-bundle",level:2},{value:"If you are using a PSR-15 compatible framework",id:"if-you-are-using-a-psr-15-compatible-framework",level:2},{value:"If you are using another framework not compatible with PSR-15",id:"if-you-are-using-another-framework-not-compatible-with-psr-15",level:2},{value:"Usage",id:"usage",level:2}],u={toc:s},d="wrapper";function h(e){let{components: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/c933a311.383732ef.js b/assets/js/c933a311.12e46a4a.js similarity index 99% rename from assets/js/c933a311.383732ef.js rename to assets/js/c933a311.12e46a4a.js index c73cc14d4..56b20b1d7 100644 --- a/assets/js/c933a311.383732ef.js +++ b/assets/js/c933a311.12e46a4a.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.04b40a4d.js b/assets/js/c953ec08.044ba5e1.js similarity index 99% rename from assets/js/c953ec08.04b40a4d.js rename to assets/js/c953ec08.044ba5e1.js index d3970aa35..ac5ef34ed 100644 --- a/assets/js/c953ec08.04b40a4d.js +++ b/assets/js/c953ec08.044ba5e1.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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.7e867049.js b/assets/js/ca36df4d.94c47d62.js similarity index 99% rename from assets/js/ca36df4d.7e867049.js rename to assets/js/ca36df4d.94c47d62.js index 943a99efd..66f895d0f 100644 --- a/assets/js/ca36df4d.7e867049.js +++ b/assets/js/ca36df4d.94c47d62.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:()=>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:"changelog",title:"Changelog",description:"7.1.0",source:"@site/docs/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/next/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/CHANGELOG.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/next/semver"}},p={},d=[{value:"7.1.0",id:"710",level:2},{value:"Breaking Changes",id:"breaking-changes",level:3},{value:"Improvements",id:"improvements",level:3},{value:"7.0.0",id:"700",level:2},{value:"Breaking Changes",id:"breaking-changes-1",level:3},{value:"New Features",id:"new-features",level:3},{value:"Improvements",id:"improvements-1",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-2",level:3},{value:"Improvements",id:"improvements-2",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}],s={toc:d},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:"710"},"7.1.0"),(0,i.yg)("h3",{id:"breaking-changes"},"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"},"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-1"},"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-1"},"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-2"},"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-2"},"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/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-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/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:()=>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:"changelog",title:"Changelog",description:"7.1.0",source:"@site/docs/CHANGELOG.md",sourceDirName:".",slug:"/changelog",permalink:"/docs/next/changelog",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/docs/CHANGELOG.md",tags:[],version:"current",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"changelog",title:"Changelog",sidebar_label:"Changelog"},sidebar:"docs",previous:{title:"Semantic versioning",permalink:"/docs/next/semver"}},p={},d=[{value:"7.1.0",id:"710",level:2},{value:"Breaking Changes",id:"breaking-changes",level:3},{value:"Improvements",id:"improvements",level:3},{value:"7.0.0",id:"700",level:2},{value:"Breaking Changes",id:"breaking-changes-1",level:3},{value:"New Features",id:"new-features",level:3},{value:"Improvements",id:"improvements-1",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-2",level:3},{value:"Improvements",id:"improvements-2",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}],s={toc:d},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:"710"},"7.1.0"),(0,i.yg)("h3",{id:"breaking-changes"},"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"},"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-1"},"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-1"},"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-2"},"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-2"},"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/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-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/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.851f28bb.js b/assets/js/caa79efa.53b67792.js similarity index 99% rename from assets/js/caa79efa.851f28bb.js rename to assets/js/caa79efa.53b67792.js index 2fcee4472..6b53ab80b 100644 --- a/assets/js/caa79efa.851f28bb.js +++ b/assets/js/caa79efa.53b67792.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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-system/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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-system/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.364564ce.js b/assets/js/cb01db44.57683fd3.js similarity index 99% rename from assets/js/cb01db44.364564ce.js rename to assets/js/cb01db44.57683fd3.js index 6167fa73f..277eac0f1 100644 --- a/assets/js/cb01db44.364564ce.js +++ b/assets/js/cb01db44.57683fd3.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.00b229fc.js b/assets/js/cc08685c.e931f2d8.js similarity index 99% rename from assets/js/cc08685c.00b229fc.js rename to assets/js/cc08685c.e931f2d8.js index 840f86171..a1cf223a9 100644 --- a/assets/js/cc08685c.00b229fc.js +++ b/assets/js/cc08685c.e931f2d8.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.14b8c14a.js b/assets/js/cc1c02fe.f50e1ffd.js similarity index 99% rename from assets/js/cc1c02fe.14b8c14a.js rename to assets/js/cc1c02fe.f50e1ffd.js index 56f35966a..0ce80574b 100644 --- a/assets/js/cc1c02fe.14b8c14a.js +++ b/assets/js/cc1c02fe.f50e1ffd.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 y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!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,y]=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}),h=(()=>{const e=s??p;return g({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{h&&l(h)}),[h]);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),y(e)}),[u,y,o]),tabValues:o}}var h=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=y(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,h.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!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,y]=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}),h=(()=>{const e=s??p;return g({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{h&&l(h)}),[h]);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),y(e)}),[u,y,o]),tabValues:o}}var h=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=y(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,h.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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.509da543.js b/assets/js/cc1f18af.993e0004.js similarity index 99% rename from assets/js/cc1f18af.509da543.js rename to assets/js/cc1f18af.993e0004.js index 0f0baa1f8..e19971cd0 100644 --- a/assets/js/cc1f18af.509da543.js +++ b/assets/js/cc1f18af.993e0004.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 d(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"),"."))}d.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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 d(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"),"."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/cd25a595.6427617e.js b/assets/js/cd25a595.cedacea9.js similarity index 99% rename from assets/js/cd25a595.6427617e.js rename to assets/js/cd25a595.cedacea9.js index b6f1b1052..198df6405 100644 --- a/assets/js/cd25a595.6427617e.js +++ b/assets/js/cd25a595.cedacea9.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.d4883c0f.js b/assets/js/cd30f404.ad234e4d.js similarity index 99% rename from assets/js/cd30f404.d4883c0f.js rename to assets/js/cd30f404.ad234e4d.js index 7c71e5432..20a0d6181 100644 --- a/assets/js/cd30f404.d4883c0f.js +++ b/assets/js/cd30f404.ad234e4d.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 d(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 c(e){const{values:a,children:n}=e;return(0,r.useMemo)((()=>{const e=a??d(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=c(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}),[d,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??d;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:d}=(0,i.a_)(),c=e=>{const a=e.currentTarget,n=p.indexOf(a),t=u[n].value;t!==o&&(d(a),s(t))},g=e=>{let a=null;switch(e.key){case"Enter":c(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:c},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:()=>d});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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features",original_id:"laravel-package-advanced"},sidebar:"version-4.1/docs",previous:{title:"Symfony specific features",permalink:"/docs/4.1/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/4.1/internals"}},p={},d=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],c={toc:d},g="wrapper";function h(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},c,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 d(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 c(e){const{values:a,children:n}=e;return(0,r.useMemo)((()=>{const e=a??d(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=c(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}),[d,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??d;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:d}=(0,i.a_)(),c=e=>{const a=e.currentTarget,n=p.indexOf(a),t=u[n].value;t!==o&&(d(a),s(t))},g=e=>{let a=null;switch(e.key){case"Enter":c(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:c},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:()=>d});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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"laravel-package-advanced",title:"Laravel package: advanced usage",sidebar_label:"Laravel specific features",original_id:"laravel-package-advanced"},sidebar:"version-4.1/docs",previous:{title:"Symfony specific features",permalink:"/docs/4.1/symfony-bundle-advanced"},next:{title:"Internals",permalink:"/docs/4.1/internals"}},p={},d=[{value:"Support for Laravel validation rules",id:"support-for-laravel-validation-rules",level:2},{value:"Support for pagination",id:"support-for-pagination",level:2},{value:"Simple paginator",id:"simple-paginator",level:3},{value:"Using GraphQLite with Eloquent efficiently",id:"using-graphqlite-with-eloquent-efficiently",level:2},{value:"Pitfalls to avoid with Eloquent",id:"pitfalls-to-avoid-with-eloquent",level:3}],c={toc:d},g="wrapper";function h(e){let{components:a,...n}=e;return(0,r.yg)(g,(0,t.A)({},c,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.560b6c61.js b/assets/js/cd699560.3152ae70.js similarity index 99% rename from assets/js/cd699560.560b6c61.js rename to assets/js/cd699560.3152ae70.js index f629df32e..dac9f278d 100644 --- a/assets/js/cd699560.560b6c61.js +++ b/assets/js/cd699560.3152ae70.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 y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!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,y]=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}),h=(()=>{const e=s??p;return g({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{h&&l(h)}),[h]);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),y(e)}),[u,y,o]),tabValues:o}}var h=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=y(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,h.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 y(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,l]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!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,y]=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}),h=(()=>{const e=s??p;return g({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{h&&l(h)}),[h]);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),y(e)}),[u,y,o]),tabValues:o}}var h=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=y(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,h.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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.b97b3b81.js b/assets/js/cddcd4e6.b0f5a7d8.js similarity index 99% rename from assets/js/cddcd4e6.b97b3b81.js rename to assets/js/cddcd4e6.b0f5a7d8.js index e882dcbe1..dea313ad6 100644 --- a/assets/js/cddcd4e6.b97b3b81.js +++ b/assets/js/cddcd4e6.b0f5a7d8.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 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))}},89848:(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-3.0/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony.",source:"@site/versioned_docs/version-3.0/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/3.0/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/symfony-bundle-advanced.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],m={toc:p},d="wrapper";function 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([[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 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))}},89848:(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-3.0/symfony-bundle-advanced",title:"Symfony bundle: advanced usage",description:"The Symfony bundle comes with a number of features to ease the integration of GraphQLite in Symfony.",source:"@site/versioned_docs/version-3.0/symfony-bundle-advanced.mdx",sourceDirName:".",slug:"/symfony-bundle-advanced",permalink:"/docs/3.0/symfony-bundle-advanced",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/symfony-bundle-advanced.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"symfony-bundle-advanced",title:"Symfony bundle: advanced usage",sidebar_label:"Symfony specific features"}},c={},p=[{value:"Login and logout",id:"login-and-logout",level:2},{value:"Schema and request security",id:"schema-and-request-security",level:2},{value:"Login using the "login" mutation",id:"login-using-the-login-mutation",level:3},{value:"Get the current user with the "me" query",id:"get-the-current-user-with-the-me-query",level:3},{value:"Logout using the "logout" mutation",id:"logout-using-the-logout-mutation",level:3},{value:"Injecting the Request",id:"injecting-the-request",level:2}],m={toc:p},d="wrapper";function 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/ce95b17c.0f107b8a.js b/assets/js/ce95b17c.d0a613b9.js similarity index 98% rename from assets/js/ce95b17c.0f107b8a.js rename to assets/js/ce95b17c.d0a613b9.js index 7283a7e2e..0981292c0 100644 --- a/assets/js/ce95b17c.0f107b8a.js +++ b/assets/js/ce95b17c.d0a613b9.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[4e3],{90428:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>h,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var a=n(58168),r=(n(96540),n(15680));n(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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:t,...n}=e;return(0,r.yg)(d,(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,"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,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>o,default:()=>h,frontMatter:()=>l,metadata:()=>i,toc:()=>s});var a=n(58168),r=(n(96540),n(15680));n(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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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:t,...n}=e;return(0,r.yg)(d,(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,"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.ee57f31d.js b/assets/js/cf877cff.06db9245.js similarity index 94% rename from assets/js/cf877cff.ee57f31d.js rename to assets/js/cf877cff.06db9245.js index 3507fda13..f925847ea 100644 --- a/assets/js/cf877cff.ee57f31d.js +++ b/assets/js/cf877cff.06db9245.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:()=>g,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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"docs",previous:{title:"GraphQLite",permalink:"/docs/"},next:{title:"Symfony bundle",permalink:"/docs/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},p,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)"))))}g.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:()=>g,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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"getting-started",title:"Getting started",sidebar_label:"Getting Started"},sidebar:"docs",previous:{title:"GraphQLite",permalink:"/docs/"},next:{title:"Symfony bundle",permalink:"/docs/symfony-bundle"}},d={},l=[],p={toc:l},c="wrapper";function g(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},p,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)"))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d07ad772.1a568f07.js b/assets/js/d07ad772.4ed10499.js similarity index 99% rename from assets/js/d07ad772.1a568f07.js rename to assets/js/d07ad772.4ed10499.js index 39ba9f17d..aa9741a62 100644 --- a/assets/js/d07ad772.1a568f07.js +++ b/assets/js/d07ad772.4ed10499.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 d(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"),"."))}d.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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 d(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"),"."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d3540d59.2377760d.js b/assets/js/d3540d59.34df5196.js similarity index 99% rename from assets/js/d3540d59.2377760d.js rename to assets/js/d3540d59.34df5196.js index c0499c5b8..2d38e0ef9 100644 --- a/assets/js/d3540d59.2377760d.js +++ b/assets/js/d3540d59.34df5196.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ddfa5556.js b/assets/js/d4446569.39c2daf1.js similarity index 99% rename from assets/js/d4446569.ddfa5556.js rename to assets/js/d4446569.39c2daf1.js index 33d54caae..e7fe14d47 100644 --- a/assets/js/d4446569.ddfa5556.js +++ b/assets/js/d4446569.39c2daf1.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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-system/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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-system/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.d35742e3.js b/assets/js/d49884c9.9a4dd072.js similarity index 99% rename from assets/js/d49884c9.d35742e3.js rename to assets/js/d49884c9.9a4dd072.js index e33a6a709..6bf4d10ec 100644 --- a/assets/js/d49884c9.d35742e3.js +++ b/assets/js/d49884c9.9a4dd072.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.3138b0b0.js b/assets/js/d4c8693b.2b550467.js similarity index 98% rename from assets/js/d4c8693b.3138b0b0.js rename to assets/js/d4c8693b.2b550467.js index 845d1fdee..0bc42dabe 100644 --- a/assets/js/d4c8693b.3138b0b0.js +++ b/assets/js/d4c8693b.2b550467.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.4f509987.js b/assets/js/d589d3a7.5a3a9b0b.js similarity index 97% rename from assets/js/d589d3a7.4f509987.js rename to assets/js/d589d3a7.5a3a9b0b.js index d7dc02eb7..3b8d215e3 100644 --- a/assets/js/d589d3a7.4f509987.js +++ b/assets/js/d589d3a7.5a3a9b0b.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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},p="wrapper";function g(t){let{components:e,...a}=t;return(0,n.yg)(p,(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)"))))}g.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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},p="wrapper";function g(t){let{components:e,...a}=t;return(0,n.yg)(p,(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)"))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d6188fd4.1f2e6f70.js b/assets/js/d6188fd4.a07234ea.js similarity index 98% rename from assets/js/d6188fd4.1f2e6f70.js rename to assets/js/d6188fd4.a07234ea.js index df97ee18b..aef38334f 100644 --- a/assets/js/d6188fd4.1f2e6f70.js +++ b/assets/js/d6188fd4.a07234ea.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/d6b4b60c.6634bc76.js b/assets/js/d6b4b60c.010a242a.js similarity index 99% rename from assets/js/d6b4b60c.6634bc76.js rename to assets/js/d6b4b60c.010a242a.js index ad0d3ab1b..de3fc1862 100644 --- a/assets/js/d6b4b60c.6634bc76.js +++ b/assets/js/d6b4b60c.010a242a.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.16a3de8b.js b/assets/js/d7067606.0c33c4b9.js similarity index 99% rename from assets/js/d7067606.16a3de8b.js rename to assets/js/d7067606.0c33c4b9.js index 61aca98a6..8904c39da 100644 --- a/assets/js/d7067606.16a3de8b.js +++ b/assets/js/d7067606.0c33c4b9.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.6bb564c4.js b/assets/js/d8037f4c.aa4c87e4.js similarity index 97% rename from assets/js/d8037f4c.6bb564c4.js rename to assets/js/d8037f4c.aa4c87e4.js index bdbe9834a..c5810fd6d 100644 --- a/assets/js/d8037f4c.6bb564c4.js +++ b/assets/js/d8037f4c.aa4c87e4.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/6.0/internals"},next:{title:"Migrating",permalink:"/docs/6.0/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},p,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."))}d.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:()=>d,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting"},sidebar:"docs",previous:{title:"Internals",permalink:"/docs/6.0/internals"},next:{title:"Migrating",permalink:"/docs/6.0/migrating"}},l={},u=[],p={toc:u},c="wrapper";function d(e){let{components:t,...o}=e;return(0,r.yg)(c,(0,n.A)({},p,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."))}d.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/d8ff000f.70099734.js b/assets/js/d8ff000f.9d93ba36.js similarity index 99% rename from assets/js/d8ff000f.70099734.js rename to assets/js/d8ff000f.9d93ba36.js index 519c5e2f6..46220dfae 100644 --- a/assets/js/d8ff000f.70099734.js +++ b/assets/js/d8ff000f.9d93ba36.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.e016ee1c.js b/assets/js/d9523c62.b56bad2f.js similarity index 99% rename from assets/js/d9523c62.e016ee1c.js rename to assets/js/d9523c62.b56bad2f.js index b15446790..9762232a3 100644 --- a/assets/js/d9523c62.e016ee1c.js +++ b/assets/js/d9523c62.b56bad2f.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.26f93eaf.js b/assets/js/db6a6f31.8f99dbe0.js similarity index 99% rename from assets/js/db6a6f31.26f93eaf.js rename to assets/js/db6a6f31.8f99dbe0.js index 5800e56f3..f7a201437 100644 --- a/assets/js/db6a6f31.26f93eaf.js +++ b/assets/js/db6a6f31.8f99dbe0.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ae27c30d.js b/assets/js/dbf2bcb3.364cf064.js similarity index 99% rename from assets/js/dbf2bcb3.ae27c30d.js rename to assets/js/dbf2bcb3.364cf064.js index ff4a74ead..e8a7a8553 100644 --- a/assets/js/dbf2bcb3.ae27c30d.js +++ b/assets/js/dbf2bcb3.364cf064.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.ea062c13.js b/assets/js/dc9a99e0.0ea91606.js similarity index 99% rename from assets/js/dc9a99e0.ea062c13.js rename to assets/js/dc9a99e0.0ea91606.js index 29319cad0..37c482b8e 100644 --- a/assets/js/dc9a99e0.ea062c13.js +++ b/assets/js/dc9a99e0.0ea91606.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),p=a(57485),o=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,o.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,p.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}))),[p,o]=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=p??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),o(e),h(e)}),[o,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:p,tabValues:o}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.a_)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=o[a].value;n!==i&&(d(t),p(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)},o.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))}},23255:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>p,default:()=>m,frontMatter:()=>i,metadata:()=>o,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"},p=void 0,o={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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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={},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/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),p=a(57485),o=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,o.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,p.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}))),[p,o]=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=p??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),o(e),h(e)}),[o,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:p,tabValues:o}=e;const s=[],{blockElementScrollPositionUntilNextRender:d}=(0,r.a_)(),c=e=>{const t=e.currentTarget,a=s.indexOf(t),n=o[a].value;n!==i&&(d(t),p(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)},o.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))}},23255:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>p,default:()=>m,frontMatter:()=>i,metadata:()=>o,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"},p=void 0,o={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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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={},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/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.759e384a.js b/assets/js/e126d786.f6d45879.js similarity index 99% rename from assets/js/e126d786.759e384a.js rename to assets/js/e126d786.f6d45879.js index ee6cd0a00..8f8158699 100644 --- a/assets/js/e126d786.759e384a.js +++ b/assets/js/e126d786.f6d45879.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.2a245732.js b/assets/js/e196b408.456456b5.js similarity index 98% rename from assets/js/e196b408.2a245732.js rename to assets/js/e196b408.456456b5.js index f68e3ea69..c01699d23 100644 --- a/assets/js/e196b408.2a245732.js +++ b/assets/js/e196b408.456456b5.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.e50032b6.js b/assets/js/e1b8bb84.3cc0d0de.js similarity index 99% rename from assets/js/e1b8bb84.e50032b6.js rename to assets/js/e1b8bb84.3cc0d0de.js index 1c47cea72..9205da87d 100644 --- a/assets/js/e1b8bb84.e50032b6.js +++ b/assets/js/e1b8bb84.3cc0d0de.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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:()=>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))}},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.a4b8dac7.js b/assets/js/e29eb381.53f21514.js similarity index 99% rename from assets/js/e29eb381.a4b8dac7.js rename to assets/js/e29eb381.53f21514.js index c2eb59fd4..1dcb8350b 100644 --- a/assets/js/e29eb381.a4b8dac7.js +++ b/assets/js/e29eb381.53f21514.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.13362052.js b/assets/js/e2e51976.c3c8fc60.js similarity index 99% rename from assets/js/e2e51976.13362052.js rename to assets/js/e2e51976.c3c8fc60.js index 45600297f..8203647e9 100644 --- a/assets/js/e2e51976.13362052.js +++ b/assets/js/e2e51976.c3c8fc60.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 g(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function h(t){let{queryString:e=!1,groupId:n}=t;const a=(0,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(!g({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]=h({queryString:n,groupId:a}),[p,b]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Dv)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),m=(()=>{const t=l??p;return g({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{m&&s(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!g({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))},g=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:g,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:()=>h,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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},g="wrapper";function h(t){let{components:e,...n}=t;return(0,r.yg)(g,(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")))}h.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 g(t){let{value:e,tabValues:n}=t;return n.some((t=>t.value===e))}function h(t){let{queryString:e=!1,groupId:n}=t;const a=(0,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(!g({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]=h({queryString:n,groupId:a}),[p,b]=function(t){let{groupId:e}=t;const n=function(t){return t?`docusaurus.tab.${t}`:null}(e),[a,o]=(0,c.Dv)(n);return[a,(0,r.useCallback)((t=>{n&&o.set(t)}),[n,o])]}({groupId:a}),m=(()=>{const t=l??p;return g({value:t,tabValues:o})?t:null})();(0,r.useLayoutEffect)((()=>{m&&s(m)}),[m]);return{selectedValue:i,selectValue:(0,r.useCallback)((t=>{if(!g({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))},g=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:g,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:()=>h,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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},g="wrapper";function h(t){let{components:e,...n}=t;return(0,r.yg)(g,(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")))}h.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e347e63a.76738bdd.js b/assets/js/e347e63a.0915f118.js similarity index 99% rename from assets/js/e347e63a.76738bdd.js rename to assets/js/e347e63a.0915f118.js index 69c21c661..16fab188a 100644 --- a/assets/js/e347e63a.76738bdd.js +++ b/assets/js/e347e63a.0915f118.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.d750a1ca.js b/assets/js/e39283a8.e3256bf2.js similarity index 99% rename from assets/js/e39283a8.d750a1ca.js rename to assets/js/e39283a8.e3256bf2.js index e3ab8c7db..86ee8f01a 100644 --- a/assets/js/e39283a8.d750a1ca.js +++ b/assets/js/e39283a8.e3256bf2.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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")," 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/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/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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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")," 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/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/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.444f2ef3.js b/assets/js/e45c611c.55637c17.js similarity index 99% rename from assets/js/e45c611c.444f2ef3.js rename to assets/js/e45c611c.55637c17.js index 2d8896f94..78ce56533 100644 --- a/assets/js/e45c611c.444f2ef3.js +++ b/assets/js/e45c611c.55637c17.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.fd7ca642.js b/assets/js/e4c5fdc3.5ba1ee13.js similarity index 98% rename from assets/js/e4c5fdc3.fd7ca642.js rename to assets/js/e4c5fdc3.5ba1ee13.js index 29795dffb..bc75023f6 100644 --- a/assets/js/e4c5fdc3.fd7ca642.js +++ b/assets/js/e4c5fdc3.5ba1ee13.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.97145ef4.js b/assets/js/e5d0e3cb.ca7ccaf8.js similarity index 99% rename from assets/js/e5d0e3cb.97145ef4.js rename to assets/js/e5d0e3cb.ca7ccaf8.js index be3f2d6d1..2ab941213 100644 --- a/assets/js/e5d0e3cb.97145ef4.js +++ b/assets/js/e5d0e3cb.ca7ccaf8.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.323d517e.js b/assets/js/e5d7b215.47184428.js similarity index 98% rename from assets/js/e5d7b215.323d517e.js rename to assets/js/e5d7b215.47184428.js index e3ef8f596..f13c65218 100644 --- a/assets/js/e5d7b215.323d517e.js +++ b/assets/js/e5d7b215.47184428.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 t=i(58168),n=(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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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,n.yg)(d,(0,t.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.yg)("p",null,(0,n.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,n.yg)("p",null,"If your framework is compatible with ",(0,n.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,n.yg)("h2",{id:"installation"},"Installation"),(0,n.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,n.yg)("pre",null,(0,n.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.yg)("h2",{id:"requirements"},"Requirements"),(0,n.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.yg)("p",null,"GraphQLite relies on the ",(0,n.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,n.yg)("a",{parentName:"p",href:"/docs/next/other-frameworks"},"PSR-15 middleware"),"."),(0,n.yg)("h2",{id:"integration"},"Integration"),(0,n.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,n.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,n.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.yg)("p",null,(0,n.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,n.yg)("pre",null,(0,n.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,n.yg)("pre",null,(0,n.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 t=i(58168),n=(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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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,n.yg)(d,(0,t.A)({},c,i,{components:r,mdxType:"MDXLayout"}),(0,n.yg)("p",null,(0,n.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,n.yg)("p",null,"If your framework is compatible with ",(0,n.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,n.yg)("h2",{id:"installation"},"Installation"),(0,n.yg)("p",null,"Open a terminal in your current project directory and run:"),(0,n.yg)("pre",null,(0,n.yg)("code",{parentName:"pre",className:"language-console"},"$ composer require thecodingmachine/graphqlite-universal-service-provider\n")),(0,n.yg)("h2",{id:"requirements"},"Requirements"),(0,n.yg)("p",null,"In order to bootstrap GraphQLite, you will need:"),(0,n.yg)("ul",null,(0,n.yg)("li",{parentName:"ul"},"A PSR-16 cache")),(0,n.yg)("p",null,"Additionally, you will have to route the HTTP requests to the underlying GraphQL library."),(0,n.yg)("p",null,"GraphQLite relies on the ",(0,n.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,n.yg)("a",{parentName:"p",href:"/docs/next/other-frameworks"},"PSR-15 middleware"),"."),(0,n.yg)("h2",{id:"integration"},"Integration"),(0,n.yg)("p",null,"Webonyx/graphql-php library requires a ",(0,n.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,n.yg)("inlineCode",{parentName:"p"},"Schema")," class."),(0,n.yg)("p",null,(0,n.yg)("a",{parentName:"p",href:"https://github.com/thecodingmachine/graphqlite-universal-service-provider"},"Checkout the the service-provider documentation")),(0,n.yg)("h2",{id:"sample-usage"},"Sample usage"),(0,n.yg)("pre",null,(0,n.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,n.yg)("pre",null,(0,n.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.0098ac60.js b/assets/js/e617c97b.0f60a620.js similarity index 99% rename from assets/js/e617c97b.0098ac60.js rename to assets/js/e617c97b.0f60a620.js index fbcca45ce..c54616d2c 100644 --- a/assets/js/e617c97b.0098ac60.js +++ b/assets/js/e617c97b.0f60a620.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.2721bbb3.js b/assets/js/e63ebe23.c78c4380.js similarity index 99% rename from assets/js/e63ebe23.2721bbb3.js rename to assets/js/e63ebe23.c78c4380.js index 33e55a8b5..32f0ae7cf 100644 --- a/assets/js/e63ebe23.2721bbb3.js +++ b/assets/js/e63ebe23.c78c4380.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.e2f7fe76.js b/assets/js/e6858589.58fb90f0.js similarity index 96% rename from assets/js/e6858589.e2f7fe76.js rename to assets/js/e6858589.58fb90f0.js index 89eab6c53..e188df789 100644 --- a/assets/js/e6858589.e2f7fe76.js +++ b/assets/js/e6858589.58fb90f0.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7143],{42495:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>a,contentTitle:()=>s,default:()=>c,frontMatter:()=>r,metadata:()=>l,toc:()=>d});var n=o(58168),i=(o(96540),o(15680));o(67443);const r={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting",original_id:"troubleshooting"},s=void 0,l={unversionedId:"troubleshooting",id:"version-3.0/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-3.0/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/3.0/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/troubleshooting.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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"}},a={},d=[],u={toc:d},g="wrapper";function c(e){let{components:t,...o}=e;return(0,i.yg)(g,(0,n.A)({},u,o,{components:t,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")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7143],{42495:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>a,contentTitle:()=>s,default:()=>c,frontMatter:()=>r,metadata:()=>l,toc:()=>d});var n=o(58168),i=(o(96540),o(15680));o(67443);const r={id:"troubleshooting",title:"Troubleshooting",sidebar_label:"Troubleshooting",original_id:"troubleshooting"},s=void 0,l={unversionedId:"troubleshooting",id:"version-3.0/troubleshooting",title:"Troubleshooting",description:"Error: Maximum function nesting level of '100' reached",source:"@site/versioned_docs/version-3.0/troubleshooting.md",sourceDirName:".",slug:"/troubleshooting",permalink:"/docs/3.0/troubleshooting",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/troubleshooting.md",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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"}},a={},d=[],u={toc:d},g="wrapper";function c(e){let{components:t,...o}=e;return(0,i.yg)(g,(0,n.A)({},u,o,{components:t,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")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e688cd7e.1765bc4b.js b/assets/js/e688cd7e.b87d4ac1.js similarity index 99% rename from assets/js/e688cd7e.1765bc4b.js rename to assets/js/e688cd7e.b87d4ac1.js index ae68c9465..155ecd5b2 100644 --- a/assets/js/e688cd7e.1765bc4b.js +++ b/assets/js/e688cd7e.b87d4ac1.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.3992b7f7.js b/assets/js/e68b092b.792b0f23.js similarity index 99% rename from assets/js/e68b092b.3992b7f7.js rename to assets/js/e68b092b.792b0f23.js index b90aeff1e..d2b7f79d2 100644 --- a/assets/js/e68b092b.3992b7f7.js +++ b/assets/js/e68b092b.792b0f23.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/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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"docs",previous:{title:"Custom types",permalink:"/docs/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"field-middlewares",title:"Adding custom annotations with Field middlewares",sidebar_label:"Custom annotations"},sidebar:"docs",previous:{title:"Custom types",permalink:"/docs/custom-types"},next:{title:"Custom argument resolving",permalink:"/docs/argument-resolving"}},d={},s=[{value:"Field middlewares",id:"field-middlewares",level:2},{value:"Annotations parsing",id:"annotations-parsing",level:2}],u={toc:s},p="wrapper";function c(e){let{components:n,...l}=e;return(0,a.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.4e9b3ab1.js b/assets/js/e7672013.c76f00ef.js similarity index 98% rename from assets/js/e7672013.4e9b3ab1.js rename to assets/js/e7672013.c76f00ef.js index d8a2156d8..946968402 100644 --- a/assets/js/e7672013.4e9b3ab1.js +++ b/assets/js/e7672013.c76f00ef.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.b2a8e665.js b/assets/js/e7ffb4b4.60104518.js similarity index 97% rename from assets/js/e7ffb4b4.b2a8e665.js rename to assets/js/e7ffb4b4.60104518.js index cc09c57d8..2e4f45ace 100644 --- a/assets/js/e7ffb4b4.b2a8e665.js +++ b/assets/js/e7ffb4b4.60104518.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2119],{7009:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>c,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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},p="wrapper";function c(t){let{components:e,...a}=t;return(0,i.yg)(p,(0,r.A)({},g,a,{components:e,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)"))))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2119],{7009:(t,e,a)=>{a.r(e),a.d(e,{assets:()=>d,contentTitle:()=>o,default:()=>c,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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},p="wrapper";function c(t){let{components:e,...a}=t;return(0,i.yg)(p,(0,r.A)({},g,a,{components:e,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)"))))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/e806c7bf.efbffd86.js b/assets/js/e806c7bf.31b41a0d.js similarity index 99% rename from assets/js/e806c7bf.efbffd86.js rename to assets/js/e806c7bf.31b41a0d.js index 20237bfe2..d549c0dbb 100644 --- a/assets/js/e806c7bf.efbffd86.js +++ b/assets/js/e806c7bf.31b41a0d.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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/e91daeb9.8678688d.js b/assets/js/e91daeb9.d0fbb140.js similarity index 99% rename from assets/js/e91daeb9.8678688d.js rename to assets/js/e91daeb9.d0fbb140.js index 3dc7a2b70..5dcdc42b8 100644 --- a/assets/js/e91daeb9.8678688d.js +++ b/assets/js/e91daeb9.d0fbb140.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 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 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))},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",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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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 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 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))},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",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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.7cc793f0.js b/assets/js/eaa287f0.a44a681c.js similarity index 99% rename from assets/js/eaa287f0.7cc793f0.js rename to assets/js/eaa287f0.a44a681c.js index 59a9a2eb2..a286197af 100644 --- a/assets/js/eaa287f0.7cc793f0.js +++ b/assets/js/eaa287f0.a44a681c.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.bd942a0d.js b/assets/js/eb333c39.5a60d0b2.js similarity index 98% rename from assets/js/eb333c39.bd942a0d.js rename to assets/js/eb333c39.5a60d0b2.js index 87d5fdf77..12af88eff 100644 --- a/assets/js/eb333c39.bd942a0d.js +++ b/assets/js/eb333c39.5a60d0b2.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.451f4735.js b/assets/js/eca0cf35.367d84d2.js similarity index 99% rename from assets/js/eca0cf35.451f4735.js rename to assets/js/eca0cf35.367d84d2.js index 4f69772f4..5a8893f38 100644 --- a/assets/js/eca0cf35.451f4735.js +++ b/assets/js/eca0cf35.367d84d2.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.f9ce14a9.js b/assets/js/ece9cf29.df346d6b.js similarity index 99% rename from assets/js/ece9cf29.f9ce14a9.js rename to assets/js/ece9cf29.df346d6b.js index c9f0530ed..6357a4c71 100644 --- a/assets/js/ece9cf29.f9ce14a9.js +++ b/assets/js/ece9cf29.df346d6b.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.686f4c9e.js b/assets/js/ed0c0463.89bcbb2f.js similarity index 99% rename from assets/js/ed0c0463.686f4c9e.js rename to assets/js/ed0c0463.89bcbb2f.js index 4c8dac63b..6f25f68ea 100644 --- a/assets/js/ed0c0463.686f4c9e.js +++ b/assets/js/ed0c0463.89bcbb2f.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.aad4a995.js b/assets/js/eec7caa6.63014402.js similarity index 99% rename from assets/js/eec7caa6.aad4a995.js rename to assets/js/eec7caa6.63014402.js index 7ee1e80bf..9af866ed0 100644 --- a/assets/js/eec7caa6.aad4a995.js +++ b/assets/js/eec7caa6.63014402.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.db4c0239.js b/assets/js/f07f4757.59bdbfef.js similarity index 99% rename from assets/js/f07f4757.db4c0239.js rename to assets/js/f07f4757.59bdbfef.js index 7a7803b0b..5ae9fe8a2 100644 --- a/assets/js/f07f4757.db4c0239.js +++ b/assets/js/f07f4757.59bdbfef.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 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))}},74810:(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-3.0/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-3.0/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/3.0/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/inheritance-interfaces.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function 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([[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 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))}},74810:(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-3.0/inheritance-interfaces",title:"Inheritance and interfaces",description:"Modeling inheritance",source:"@site/versioned_docs/version-3.0/inheritance-interfaces.mdx",sourceDirName:".",slug:"/inheritance-interfaces",permalink:"/docs/3.0/inheritance-interfaces",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/inheritance-interfaces.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"inheritance-interfaces",title:"Inheritance and interfaces",sidebar_label:"Inheritance and interfaces"}},o={},u=[{value:"Modeling inheritance",id:"modeling-inheritance",level:2},{value:"Mapping interfaces",id:"mapping-interfaces",level:2},{value:"Implementing interfaces",id:"implementing-interfaces",level:3},{value:"Interfaces without an explicit implementing type",id:"interfaces-without-an-explicit-implementing-type",level:3}],m={toc:u},d="wrapper";function 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/f2710c27.d98f0418.js b/assets/js/f2710c27.506e278f.js similarity index 98% rename from assets/js/f2710c27.d98f0418.js rename to assets/js/f2710c27.506e278f.js index af3945e1a..e4de0b9c8 100644 --- a/assets/js/f2710c27.d98f0418.js +++ b/assets/js/f2710c27.506e278f.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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}],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/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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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}],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/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.0c1b1123.js b/assets/js/f309eabc.5e793aef.js similarity index 99% rename from assets/js/f309eabc.0c1b1123.js rename to assets/js/f309eabc.5e793aef.js index d79ede8b0..cdd2fd611 100644 --- a/assets/js/f309eabc.0c1b1123.js +++ b/assets/js/f309eabc.5e793aef.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.b7e57141.js b/assets/js/f48e2589.03716c7f.js similarity index 97% rename from assets/js/f48e2589.b7e57141.js rename to assets/js/f48e2589.03716c7f.js index 135525648..d4c252233 100644 --- a/assets/js/f48e2589.b7e57141.js +++ b/assets/js/f48e2589.03716c7f.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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=[],p={toc:l},c="wrapper";function g(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},p,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)"))))}g.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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=[],p={toc:l},c="wrapper";function g(e){let{components:t,...a}=e;return(0,i.yg)(c,(0,r.A)({},p,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)"))))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f4e1d1ba.fac9d2e7.js b/assets/js/f4e1d1ba.b8330e7b.js similarity index 98% rename from assets/js/f4e1d1ba.fac9d2e7.js rename to assets/js/f4e1d1ba.b8330e7b.js index 673c47324..3b9d50b28 100644 --- a/assets/js/f4e1d1ba.fac9d2e7.js +++ b/assets/js/f4e1d1ba.b8330e7b.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.816e2b9e.js b/assets/js/f5b0a435.dab0a149.js similarity index 99% rename from assets/js/f5b0a435.816e2b9e.js rename to assets/js/f5b0a435.dab0a149.js index a82264c8d..c0136f5c2 100644 --- a/assets/js/f5b0a435.816e2b9e.js +++ b/assets/js/f5b0a435.dab0a149.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 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,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=y(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(!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}))),[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 m({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{h&&i(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}`);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_)(),y=e=>{const n=e.currentTarget,a=o.indexOf(n),t=u[a].value;t!==i&&(c(n),s(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:i===n?0:-1,"aria-selected":i===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":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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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}],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/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 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,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=y(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(!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}))),[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 m({value:e,tabValues:l})?e:null})();(0,p.useLayoutEffect)((()=>{h&&i(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}`);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_)(),y=e=>{const n=e.currentTarget,a=o.indexOf(n),t=u[a].value;t!==i&&(c(n),s(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:i===n?0:-1,"aria-selected":i===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":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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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}],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/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.e790e2e9.js b/assets/js/f7c03581.f154556e.js similarity index 99% rename from assets/js/f7c03581.e790e2e9.js rename to assets/js/f7c03581.f154556e.js index eeb9d1758..33fad400e 100644 --- a/assets/js/f7c03581.e790e2e9.js +++ b/assets/js/f7c03581.f154556e.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.01cab4f0.js b/assets/js/f9063551.127e931e.js similarity index 99% rename from assets/js/f9063551.01cab4f0.js rename to assets/js/f9063551.127e931e.js index 35b9b44cf..dae3a8b9e 100644 --- a/assets/js/f9063551.01cab4f0.js +++ b/assets/js/f9063551.127e931e.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"version-4.2/docs",previous:{title:"Custom annotations",permalink:"/docs/4.2/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/4.2/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function g(e){let{components:a,...n}=e;return(0,r.yg)(d,(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".'))}g.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:()=>g,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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"argument-resolving",title:"Extending argument resolving",sidebar_label:"Custom argument resolving"},sidebar:"version-4.2/docs",previous:{title:"Custom annotations",permalink:"/docs/4.2/field-middlewares"},next:{title:"Extending an input type",permalink:"/docs/4.2/extend-input-type"}},s={},p=[{value:"Annotations parsing",id:"annotations-parsing",level:2},{value:"Writing the parameter middleware",id:"writing-the-parameter-middleware",level:2},{value:"Registering a parameter middleware",id:"registering-a-parameter-middleware",level:2}],m={toc:p},d="wrapper";function g(e){let{components:a,...n}=e;return(0,r.yg)(d,(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".'))}g.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/f94b062c.e77a6f79.js b/assets/js/f94b062c.a92d86b1.js similarity index 99% rename from assets/js/f94b062c.e77a6f79.js rename to assets/js/f94b062c.a92d86b1.js index d2dd1334a..db376d936 100644 --- a/assets/js/f94b062c.e77a6f79.js +++ b/assets/js/f94b062c.a92d86b1.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.2f02d562.js b/assets/js/f9511b3d.606bb160.js similarity index 99% rename from assets/js/f9511b3d.2f02d562.js rename to assets/js/f9511b3d.606bb160.js index 9e149043f..f83bded12 100644 --- a/assets/js/f9511b3d.2f02d562.js +++ b/assets/js/f9511b3d.606bb160.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),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 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}),[c,m]=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),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 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=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:()=>p,contentTitle:()=>u,default:()=>h,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-3.0/extend_input_type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-3.0/extend_input_type.mdx",sourceDirName:".",slug:"/extend_input_type",permalink:"/docs/3.0/extend_input_type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/extend_input_type.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type"}},p={},c=[],d={toc:c},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),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 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}),[c,m]=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),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 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=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:()=>p,contentTitle:()=>u,default:()=>h,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-3.0/extend_input_type",title:"Extending an input type",description:"Available in GraphQLite 4.0+",source:"@site/versioned_docs/version-3.0/extend_input_type.mdx",sourceDirName:".",slug:"/extend_input_type",permalink:"/docs/3.0/extend_input_type",draft:!1,editUrl:"https://github.com/thecodingmachine/graphqlite/edit/master/website/versioned_docs/version-3.0/extend_input_type.mdx",tags:[],version:"3.0",lastUpdatedBy:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"extend_input_type",title:"Extending an input type",sidebar_label:"Extending an input type"}},p={},c=[],d={toc:c},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.dd0a6e95.js b/assets/js/f9af357c.7717f183.js similarity index 99% rename from assets/js/f9af357c.dd0a6e95.js rename to assets/js/f9af357c.7717f183.js index dc0b6cadb..4d8967b4a 100644 --- a/assets/js/f9af357c.dd0a6e95.js +++ b/assets/js/f9af357c.7717f183.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 p(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 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,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=p(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}))),[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 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),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_)(),p=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},h=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 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:h,onClick:p},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"version-5.0/docs",previous:{title:"User input validation",permalink:"/docs/5.0/validation"},next:{title:"Fine grained security",permalink:"/docs/5.0/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(h,(0,a.A)({},p,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 p(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 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,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=p(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}))),[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 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),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_)(),p=e=>{const n=e.currentTarget,t=c.indexOf(n),a=s[t].value;a!==l&&(d(n),u(a))},h=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 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:h,onClick:p},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 2024",frontMatter:{id:"authentication-authorization",title:"Authentication and authorization",sidebar_label:"Authentication and authorization"},sidebar:"version-5.0/docs",previous:{title:"User input validation",permalink:"/docs/5.0/validation"},next:{title:"Fine grained security",permalink:"/docs/5.0/fine-grained-security"}},c={},d=[{value:"@Logged and @Right annotations",id:"logged-and-right-annotations",level:2},{value:"Not throwing errors",id:"not-throwing-errors",level:2},{value:"Injecting the current user as a parameter",id:"injecting-the-current-user-as-a-parameter",level:2},{value:"Hiding fields / queries / mutations",id:"hiding-fields--queries--mutations",level:2}],p={toc:d},h="wrapper";function g(e){let{components:n,...t}=e;return(0,r.yg)(h,(0,a.A)({},p,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.c3d8a378.js b/assets/js/fa1dd05c.c6180736.js similarity index 99% rename from assets/js/fa1dd05c.c3d8a378.js rename to assets/js/fa1dd05c.c6180736.js index 09d863cf7..28e80e1ab 100644 --- a/assets/js/fa1dd05c.c3d8a378.js +++ b/assets/js/fa1dd05c.c6180736.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.62291ed9.js b/assets/js/fa41c0e9.852637a4.js similarity index 99% rename from assets/js/fa41c0e9.62291ed9.js rename to assets/js/fa41c0e9.852637a4.js index 155ccefcb..a713a26ba 100644 --- a/assets/js/fa41c0e9.62291ed9.js +++ b/assets/js/fa41c0e9.852637a4.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 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))}},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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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}],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/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 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))}},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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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}],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/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.af7323d0.js b/assets/js/fe153c07.368664ec.js similarity index 99% rename from assets/js/fe153c07.af7323d0.js rename to assets/js/fe153c07.368664ec.js index 53dbaf0c1..47f397fba 100644 --- a/assets/js/fe153c07.af7323d0.js +++ b/assets/js/fe153c07.368664ec.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:"dependabot[bot]",lastUpdatedAt:1728277176,formattedLastUpdatedAt:"Oct 7, 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:"dependabot[bot]",lastUpdatedAt:1728335934,formattedLastUpdatedAt:"Oct 7, 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.7bb6db3c.js b/assets/js/runtime~main.a29417e8.js similarity index 61% rename from assets/js/runtime~main.7bb6db3c.js rename to assets/js/runtime~main.a29417e8.js index 9360fe521..a7bd0dbe1 100644 --- a/assets/js/runtime~main.7bb6db3c.js +++ b/assets/js/runtime~main.a29417e8.js @@ -1 +1 @@ -(()=>{"use strict";var e,a,c,f,b={},d={};function r(e){var a=d[e];if(void 0!==a)return a.exports;var c=d[e]={exports:{}};return b[e].call(c.exports,c,c.exports,r),c.exports}r.m=b,e=[],r.O=(a,c,f,b)=>{if(!c){var d=1/0;for(i=0;i=b)&&Object.keys(r.O).every((e=>r.O[e](c[o])))?c.splice(o--,1):(t=!1,b0&&e[i-1][2]>b;i--)e[i]=e[i-1];e[i]=[c,f,b]},r.n=e=>{var a=e&&e.__esModule?()=>e.default:()=>e;return r.d(a,{a:a}),a},c=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(e,f){if(1&f&&(e=this(e)),8&f)return e;if("object"==typeof e&&e){if(4&f&&e.__esModule)return e;if(16&f&&"function"==typeof e.then)return e}var b=Object.create(null);r.r(b);var d={};a=a||[null,c({}),c([]),c(c)];for(var t=2&f&&e;"object"==typeof t&&!~a.indexOf(t);t=c(t))Object.getOwnPropertyNames(t).forEach((a=>d[a]=()=>e[a]));return d.default=()=>e,r.d(b,d),b},r.d=(e,a)=>{for(var c in a)r.o(a,c)&&!r.o(e,c)&&Object.defineProperty(e,c,{enumerable:!0,get:a[c]})},r.f={},r.e=e=>Promise.all(Object.keys(r.f).reduce(((a,c)=>(r.f[c](e,a),a)),[])),r.u=e=>"assets/js/"+({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",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",1604:"4dd5816e",1653:"21cde469",1661:"d8ff000f",1674:"2f36012a",1766:"e39283a8",1776:"23794275",1886:"b4657038",1894:"aa5b6080",1898:"95576100",1930:"55c77f1e",1950:"23a8ac29",1968:"c3701568",1985:"27258a7d",2032:"9000b231",2076:"common",2112:"1ea13486",2113:"cd25a595",2119:"e7ffb4b4",2138:"1a4e3797",2156:"4d049718",2174:"07666c14",2187:"dc9a99e0",2207:"1aa05129",2227:"0db959c8",2230:"8b6bafea",2235:"3d2d0a86",2248:"c275698c",2275:"5ececfab",2301:"a9125b44",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",3576:"82395e72",3585:"3f944aba",3610:"579cc8d4",3613:"22e1e32f",3642:"263ebc7a",3672:"b103c05a",3693:"5a9b411c",3701:"8d81badd",3712:"d49884c9",3723:"1428bdad",3765:"0343976d",3781:"b7442939",3820:"24aca886",3955:"aba5bf07",3962:"16565e6a",4e3:"ce95b17c",4017:"9073923c",4021:"03abab96",4032:"56279b5e",4053:"78da31a1",4054:"20540af3",4103:"d07ad772",4116:"cddcd4e6",4122:"5ffc8074",4224:"a16ee953",4225:"38317547",4253:"87089bce",4279:"610e7425",4324:"e806c7bf",4330:"65b8d1d1",4366:"16017aa6",4368:"56af72f6",4393:"27e787ca",4422:"18d6c9c9",4438:"7afb60b1",4474:"a7159008",4485:"59b1a96c",4513:"d3540d59",4548:"d8037f4c",4565:"7b54f5d5",4620:"05fed6b1",4664:"e4c5fdc3",4671:"1d703573",4690:"f48e2589",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",5091:"05e8cfc0",5099:"1b1927f4",5138:"b4aea2ce",5180:"366cfce3",5198:"143f7888",5235:"6fe30f11",5281:"cd699560",5282:"eec7caa6",5316:"c8bdc4df",5356:"60d99771",5362:"323a980a",5409:"38cf1c7a",5511:"fa1dd05c",5515:"cc08685c",5518:"e347e63a",5526:"96877411",5547:"565a5567",5558:"3d0eb74d",5619:"7bf967bc",5646:"612b773e",5675:"5285d58e",5738:"eb333c39",5747:"b370b50c",5761:"0fad1f8b",5762:"6c124661",5779:"85c72337",5832:"bb9fe7c3",5856:"90e0b7fd",5884:"e29eb381",5923:"27b414e3",5981:"0d7bb119",6009:"8299d165",6053:"17cca601",6086:"136c1ee9",6088:"13b4aeb1",6095:"741df2ae",6123:"a2d3d8d2",6145:"2355609d",6151:"c933a311",6158:"0fd21208",6192:"c69dda99",6209:"78619623",6219:"a91c1a62",6266:"be1f0304",6337:"a28aff23",6361:"d74b5642",6364:"d4a334ea",6408:"107b7a36",6427:"b42f5805",6473:"107d11ee",6481:"2014e4e3",6523:"8bf32d27",6537:"4a2da18c",6556:"d6b4b60c",6579:"d7067606",6599:"029c6d75",6621:"61c7d915",6628:"b94a1068",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",7042:"12d3ef9e",7045:"72be5fd7",7110:"9749ab4a",7116:"4194805f",7141:"85339969",7143:"e6858589",7200:"1520c72c",7248:"e38ecde0",7258:"f9511b3d",7321:"26662da3",7326:"673df5d6",7341:"f07f4757",7362:"766e1cc8",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",7906:"b06c439f",7924:"d589d3a7",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",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",8621:"4a07aaf0",8628:"5881f7ec",8633:"07c49ebd",8688:"4d00e03a",8703:"cb01db44",8714:"1be78505",8718:"75cc8326",8722:"64947e00",8735:"2917b31e",8798:"6cfcfcfb",8868:"f9063551",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",9097:"102de343",9127:"2b26025e",9158:"8c95fc16",9227:"7c27e34c",9249:"c329487f",9255:"0ef60658",9262:"9279cea7",9271:"7810a993",9282:"d4c8693b",9336:"5d7590c2",9439:"8f951ce3",9441:"a55b0daf",9445:"6c6ce37c",9454:"5bc7272e",9472:"4c7f7507",9581:"4f30448a",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",9949:"a1e3d512"}[e]||e)+"."+{2:"2a245732",40:"af88d16b",68:"1e3d8131",79:"10e1b4b0",81:"57520c92",104:"7431f3bd",109:"6820bbdd",152:"62df2119",211:"3e38ddd7",222:"73a284a0",229:"ec7dc3fc",247:"30f90fdb",288:"fcf84c6a",321:"d98f0418",324:"0c1b1123",362:"52279798",416:"85e975e8",436:"07386ae0",458:"b4e123c4",464:"e6f82b19",481:"fb4df112",501:"50645db0",514:"2dec6eeb",521:"7a129435",552:"f62c70b4",573:"cdb311ab",629:"fa1f1757",630:"efbab152",651:"e0206554",663:"c33ad6bb",770:"e790e2e9",776:"759e384a",835:"600c339c",862:"12b37f8d",932:"9bb42ee8",958:"1f0fc197",1027:"c60be34d",1039:"451f4735",1062:"f4c630d8",1084:"8b170ae8",1126:"faf621ba",1133:"7cc793f0",1141:"e63e72c1",1188:"d3c7ec0b",1190:"0ed36bbc",1235:"f2de6ddf",1245:"9b4e4601",1264:"fb2d6eb2",1289:"77711b74",1308:"437fdf09",1340:"a1b41e48",1345:"ea5ae136",1431:"b2e2ea24",1443:"ea6539f6",1465:"e016ee1c",1481:"df74297c",1505:"12aee849",1538:"62291ed9",1565:"4540c36c",1585:"462347e3",1604:"1347aa25",1653:"2dda92b3",1661:"70099734",1674:"6f491d09",1766:"d750a1ca",1774:"9b58a5d2",1776:"be36c6f0",1886:"0a64f0ff",1894:"8403baf7",1898:"21e23958",1930:"00046a46",1950:"6f8e7fa6",1968:"24a3bd1a",1985:"11b80646",2032:"e4f1d685",2076:"8b81e25b",2112:"8e8b73ef",2113:"6427617e",2119:"b2a8e665",2138:"d6eaf3f8",2156:"bd40789e",2174:"9aceff08",2187:"ea062c13",2207:"a3079b3b",2227:"cd0b2ed7",2230:"c0ebbd9d",2235:"82169c25",2248:"738c0c33",2275:"321e03dd",2301:"ea36bda7",2347:"e8721d31",2358:"60b0926d",2369:"d9e3d7f8",2400:"af9426ef",2421:"fac9d2e7",2459:"57911023",2491:"b48d6e58",2589:"f4ad5c07",2592:"7d38c4e5",2596:"86bf69c5",2600:"4e9b3ab1",2605:"317dd843",2634:"e0be6be1",2674:"7e867049",2676:"75d547c0",2720:"4ac6e79a",2743:"9fc68b60",2784:"051152f6",2830:"54ec31ba",2858:"e5209db4",2862:"672c2963",2917:"e248315d",2935:"c73ffdf3",2952:"aeb7afc4",2958:"26f93eaf",2960:"07bf472c",2962:"b23e918f",2964:"eb057b4d",2965:"c56b680a",2998:"5aab8eff",3088:"ff085183",3126:"89b3df88",3137:"634f36b4",3177:"509da543",3195:"39a52354",3196:"d7d64164",3308:"4888f0d5",3332:"30d486bb",3343:"06097821",3355:"4a59bbf6",3359:"8678688d",3382:"e2584029",3419:"182b31ca",3449:"0098ac60",3457:"cd22f35c",3460:"bc507d40",3468:"fe37ea89",3507:"979607ae",3576:"32f48466",3585:"83281771",3610:"ed347d2a",3613:"46a87359",3642:"fd45594c",3672:"abdaf47c",3693:"ce6f95a4",3701:"81c8237f",3712:"d35742e3",3723:"6eaa2756",3765:"3e3be5ef",3781:"f1dfeb88",3820:"7f44594c",3955:"035001c1",3962:"94dbe306",4e3:"0f107b8a",4017:"2450bdcb",4021:"1f8b34ea",4032:"9367e8fe",4053:"8e7ba28c",4054:"bc6f4eb1",4103:"1a568f07",4116:"b97b3b81",4122:"41ae9a58",4224:"b2b49229",4225:"f454350d",4253:"e0da2805",4279:"d2835569",4324:"efbffd86",4330:"8d1b90a0",4366:"3eccad0d",4368:"5b19550c",4393:"b3ead152",4422:"9b1b6d63",4438:"a34d9d6f",4474:"64938b3f",4485:"c8c5d980",4513:"2377760d",4548:"6bb564c4",4565:"b5df9ba2",4620:"5db9e3a1",4664:"fd7ca642",4671:"c3571e4c",4690:"b7e57141",4716:"5b47d0d7",4761:"a9f97779",4762:"6102f5c2",4773:"e70e6fa1",4779:"ee5d6717",4780:"d4c1e857",4803:"6f61e4dd",4805:"054a55e6",4807:"ddfa5556",4827:"45a05f02",4840:"1765bc4b",4843:"3f9b7190",4876:"e3ac7f51",4884:"36d2c5e5",4893:"1a01299d",4919:"67b98c1e",4954:"ecb27e90",4955:"f3cfb108",4978:"97145ef4",4981:"3b18a39d",5e3:"df37da76",5011:"04b40a4d",5049:"d803a9da",5091:"50d9e5fd",5099:"569471ed",5138:"b8c1c91c",5180:"4f5e8a84",5198:"f3942f77",5235:"63909169",5281:"560b6c61",5282:"aad4a995",5316:"e0efc303",5356:"6eee9b87",5362:"6b82ac7e",5409:"c56a066d",5511:"c3d8a378",5515:"00b229fc",5518:"76738bdd",5526:"c0200494",5547:"249b1f26",5558:"c0a1bbde",5619:"02928b46",5646:"7d6b0229",5675:"92cac4ae",5738:"bd942a0d",5747:"ded65cc0",5761:"8417400f",5762:"7cbe5021",5779:"1def6368",5832:"5f6f8397",5856:"d1dbb559",5884:"a4b8dac7",5923:"20ddf17d",5981:"9167846c",6009:"5a2348ca",6053:"007c3177",6086:"ee344fe1",6088:"f687627c",6095:"d7ee228b",6123:"8e3e1cb6",6145:"ec196a8f",6151:"383732ef",6158:"cef60eb6",6192:"24f7f4ac",6209:"5a6df041",6219:"2f51963a",6266:"730884bb",6337:"1711f5a4",6361:"e7db4435",6364:"a2e3b42d",6408:"67eb69dc",6427:"3e26017e",6473:"617e845b",6481:"9a25270f",6523:"5148b85d",6537:"4eb1119f",6556:"6634bc76",6579:"16a3de8b",6599:"34cc9a73",6621:"ddc67bf7",6628:"989eaf9b",6700:"60a413eb",6714:"ef9097a7",6729:"33beb644",6730:"27875216",6766:"de282c9d",6874:"3356cab1",6894:"cfc4398d",6912:"5c47ead6",6918:"a43926d8",6924:"88a4d717",6925:"21183fdc",6931:"f79d3873",6961:"82e55cef",6972:"04610a44",6981:"f9ce14a9",6984:"bc402124",6986:"76a36fb7",7035:"8a2fadd5",7042:"2316a90f",7045:"72da73d5",7110:"7572e404",7116:"6b3b89b3",7141:"0793324f",7143:"e2f7fe76",7200:"8a60f2ff",7248:"d9018415",7258:"2f02d562",7321:"c3e74a31",7326:"895ad17e",7341:"db4c0239",7362:"007f2971",7373:"816e2b9e",7382:"4bbdece7",7471:"22dde59a",7483:"4f0f3c44",7492:"14b8c14a",7542:"3aec4aef",7544:"db3a0eb9",7575:"1b840764",7591:"bd784f60",7696:"5c74cb1b",7735:"9c598b07",7757:"cb57eedc",7800:"bc73ad97",7846:"ba2fa99a",7858:"26a332e9",7906:"1e48dcce",7924:"4f509987",7940:"6e1fd2a9",7942:"cedd99eb",8023:"2688abf0",8025:"ae27c30d",8028:"5a41a9e3",8042:"be7c1a69",8055:"e50032b6",8059:"af7323d0",8060:"19fef1a9",8087:"3340519d",8093:"250a7b15",8100:"410100a2",8107:"444f2ef3",8112:"3c43838b",8158:"5d3c0904",8166:"2a377d4d",8173:"3992b7f7",8177:"ee57f31d",8194:"63eb0f08",8260:"2721bbb3",8267:"e7054e4a",8309:"74ac082a",8313:"7edce05a",8327:"dd0a6e95",8350:"1aaa0aca",8357:"9e1d2104",8372:"6e73b6ce",8401:"66024bca",8414:"d13d334d",8457:"714400f3",8470:"15824987",8478:"87e9f636",8483:"212ed806",8526:"8aa4dd2e",8542:"a0a8a034",8548:"89b2ce95",8581:"be8ffae5",8621:"ac98ae89",8628:"00fefab5",8633:"3ead5716",8688:"9dff7708",8703:"364564ce",8714:"1e2a6aa3",8718:"435bc032",8722:"ed002f1f",8735:"4ec91853",8798:"538269ec",8868:"01cab4f0",8873:"37f744be",8913:"1f670d9b",8919:"2a3df866",8933:"e77a6f79",8945:"13362052",8950:"686f4c9e",8997:"83af7d17",9008:"0594428c",9013:"ec32e8ef",9026:"00d5dde8",9032:"cfa95698",9040:"323d517e",9062:"851f28bb",9092:"a4397b07",9097:"cac6183f",9127:"a2d49345",9158:"191afaf6",9227:"c005f810",9249:"e61d729d",9255:"3a8223fb",9262:"fe498c74",9271:"263785f9",9282:"3138b0b0",9336:"d21d7c9f",9439:"686bd959",9441:"8b9c7c4f",9445:"00a01a79",9454:"0771ddb5",9472:"c8dd7aab",9581:"cc668b1d",9606:"1f23575a",9624:"3cc314c9",9661:"d4883c0f",9717:"a654a515",9742:"bdb67856",9775:"74330fc8",9778:"15d9be2f",9793:"81068cea",9798:"6820b216",9810:"614c1383",9828:"1f2e6f70",9866:"760f22fa",9870:"3c6e0fa6",9949:"5f53de34"}[e]+".js",r.miniCssF=e=>{},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,a)=>Object.prototype.hasOwnProperty.call(e,a),f={},r.l=(e,a,c,b)=>{if(f[e])f[e].push(a);else{var d,t;if(void 0!==c)for(var o=document.getElementsByTagName("script"),n=0;n{d.onerror=d.onload=null,clearTimeout(l);var b=f[e];if(delete f[e],d.parentNode&&d.parentNode.removeChild(d),b&&b.forEach((e=>e(c))),a)return a(c)},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",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",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","4dd5816e":"1604","21cde469":"1653",d8ff000f:"1661","2f36012a":"1674",e39283a8:"1766",b4657038:"1886",aa5b6080:"1894","55c77f1e":"1930","23a8ac29":"1950",c3701568:"1968","27258a7d":"1985","9000b231":"2032",common:"2076","1ea13486":"2112",cd25a595:"2113",e7ffb4b4:"2119","1a4e3797":"2138","4d049718":"2156","07666c14":"2174",dc9a99e0:"2187","1aa05129":"2207","0db959c8":"2227","8b6bafea":"2230","3d2d0a86":"2235",c275698c:"2248","5ececfab":"2275",a9125b44:"2301","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","82395e72":"3576","3f944aba":"3585","579cc8d4":"3610","22e1e32f":"3613","263ebc7a":"3642",b103c05a:"3672","5a9b411c":"3693","8d81badd":"3701",d49884c9:"3712","1428bdad":"3723","0343976d":"3765",b7442939:"3781","24aca886":"3820",aba5bf07:"3955","16565e6a":"3962",ce95b17c:"4000","9073923c":"4017","03abab96":"4021","56279b5e":"4032","78da31a1":"4053","20540af3":"4054",d07ad772:"4103",cddcd4e6:"4116","5ffc8074":"4122",a16ee953:"4224","87089bce":"4253","610e7425":"4279",e806c7bf:"4324","65b8d1d1":"4330","16017aa6":"4366","56af72f6":"4368","27e787ca":"4393","18d6c9c9":"4422","7afb60b1":"4438",a7159008:"4474","59b1a96c":"4485",d3540d59:"4513",d8037f4c:"4548","7b54f5d5":"4565","05fed6b1":"4620",e4c5fdc3:"4664","1d703573":"4671",f48e2589:"4690",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","05e8cfc0":"5091","1b1927f4":"5099",b4aea2ce:"5138","366cfce3":"5180","143f7888":"5198","6fe30f11":"5235",cd699560:"5281",eec7caa6:"5282",c8bdc4df:"5316","60d99771":"5356","323a980a":"5362","38cf1c7a":"5409",fa1dd05c:"5511",cc08685c:"5515",e347e63a:"5518","565a5567":"5547","3d0eb74d":"5558","7bf967bc":"5619","612b773e":"5646","5285d58e":"5675",eb333c39:"5738",b370b50c:"5747","0fad1f8b":"5761","6c124661":"5762","85c72337":"5779",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",a91c1a62:"6219",be1f0304:"6266",a28aff23:"6337",d74b5642:"6361",d4a334ea:"6364","107b7a36":"6408",b42f5805:"6427","107d11ee":"6473","2014e4e3":"6481","8bf32d27":"6523","4a2da18c":"6537",d6b4b60c:"6556",d7067606:"6579","029c6d75":"6599","61c7d915":"6621",b94a1068:"6628","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","12d3ef9e":"7042","72be5fd7":"7045","9749ab4a":"7110","4194805f":"7116",e6858589:"7143","1520c72c":"7200",e38ecde0:"7248",f9511b3d:"7258","26662da3":"7321","673df5d6":"7326",f07f4757:"7341","766e1cc8":"7362",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",b06c439f:"7906",d589d3a7:"7924",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","6c4340be":"8350",aebf35b6:"8357","57f5c28c":"8372",c0fa6485:"8414","509d2004":"8457","1ba75d10":"8470","2d4548df":"8478",acbaac14:"8483",b8487569:"8526",b9d6d6e5:"8542","346bcb92":"8548","935f2afb":"8581","4a07aaf0":"8621","5881f7ec":"8628","07c49ebd":"8633","4d00e03a":"8688",cb01db44:"8703","1be78505":"8714","75cc8326":"8718","64947e00":"8722","2917b31e":"8735","6cfcfcfb":"8798",f9063551:"8868",bf2a5963:"8919",f94b062c:"8933",e2e51976:"8945",ed0c0463:"8950","4a060504":"8997","24ac61c7":"9008","9d9f8394":"9013",bd2c4a98:"9026","21637dff":"9032",e5d7b215:"9040",caa79efa:"9062","2ef99682":"9092","102de343":"9097","2b26025e":"9127","8c95fc16":"9158","7c27e34c":"9227",c329487f:"9249","0ef60658":"9255","9279cea7":"9262","7810a993":"9271",d4c8693b:"9282","5d7590c2":"9336","8f951ce3":"9439",a55b0daf:"9441","6c6ce37c":"9445","5bc7272e":"9454","4c7f7507":"9472","4f30448a":"9581","5792f9ba":"9606","2e301473":"9624",cd30f404:"9661","976f6afc":"9717","820db038":"9742","9d336ee4":"9778","0370fbfb":"9793","58e6b30f":"9798","859fcda7":"9810",d6188fd4:"9828",a99e9943:"9866","7515d7ec":"9870",a1e3d512:"9949"}[e]||e,r.p+r.u(e)},(()=>{var e={5354:0,1869:0};r.f.j=(a,c)=>{var f=r.o(e,a)?e[a]:void 0;if(0!==f)if(f)c.push(f[2]);else if(/^(1869|5354)$/.test(a))e[a]=0;else{var b=new Promise(((c,b)=>f=e[a]=[c,b]));c.push(f[2]=b);var d=r.p+r.u(a),t=new Error;r.l(d,(c=>{if(r.o(e,a)&&(0!==(f=e[a])&&(e[a]=void 0),f)){var b=c&&("load"===c.type?"missing":c.type),d=c&&c.target&&c.target.src;t.message="Loading chunk "+a+" failed.\n("+b+": "+d+")",t.name="ChunkLoadError",t.type=b,t.request=d,f[1](t)}}),"chunk-"+a,a)}},r.O.j=a=>0===e[a];var a=(a,c)=>{var f,b,d=c[0],t=c[1],o=c[2],n=0;if(d.some((a=>0!==e[a]))){for(f in t)r.o(t,f)&&(r.m[f]=t[f]);if(o)var i=o(r)}for(a&&a(c);n{"use strict";var e,a,c,d,f={},b={};function r(e){var a=b[e];if(void 0!==a)return a.exports;var c=b[e]={exports:{}};return f[e].call(c.exports,c,c.exports,r),c.exports}r.m=f,e=[],r.O=(a,c,d,f)=>{if(!c){var b=1/0;for(i=0;i=f)&&Object.keys(r.O).every((e=>r.O[e](c[o])))?c.splice(o--,1):(t=!1,f0&&e[i-1][2]>f;i--)e[i]=e[i-1];e[i]=[c,d,f]},r.n=e=>{var a=e&&e.__esModule?()=>e.default:()=>e;return r.d(a,{a:a}),a},c=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(e,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 f=Object.create(null);r.r(f);var b={};a=a||[null,c({}),c([]),c(c)];for(var t=2&d&&e;"object"==typeof t&&!~a.indexOf(t);t=c(t))Object.getOwnPropertyNames(t).forEach((a=>b[a]=()=>e[a]));return b.default=()=>e,r.d(f,b),f},r.d=(e,a)=>{for(var c in a)r.o(a,c)&&!r.o(e,c)&&Object.defineProperty(e,c,{enumerable:!0,get:a[c]})},r.f={},r.e=e=>Promise.all(Object.keys(r.f).reduce(((a,c)=>(r.f[c](e,a),a)),[])),r.u=e=>"assets/js/"+({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",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",1604:"4dd5816e",1653:"21cde469",1661:"d8ff000f",1674:"2f36012a",1766:"e39283a8",1776:"23794275",1886:"b4657038",1894:"aa5b6080",1898:"95576100",1930:"55c77f1e",1950:"23a8ac29",1968:"c3701568",1985:"27258a7d",2032:"9000b231",2076:"common",2112:"1ea13486",2113:"cd25a595",2119:"e7ffb4b4",2138:"1a4e3797",2156:"4d049718",2174:"07666c14",2187:"dc9a99e0",2207:"1aa05129",2227:"0db959c8",2230:"8b6bafea",2235:"3d2d0a86",2248:"c275698c",2275:"5ececfab",2301:"a9125b44",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",3576:"82395e72",3585:"3f944aba",3610:"579cc8d4",3613:"22e1e32f",3642:"263ebc7a",3672:"b103c05a",3693:"5a9b411c",3701:"8d81badd",3712:"d49884c9",3723:"1428bdad",3765:"0343976d",3781:"b7442939",3820:"24aca886",3955:"aba5bf07",3962:"16565e6a",4e3:"ce95b17c",4017:"9073923c",4021:"03abab96",4032:"56279b5e",4053:"78da31a1",4054:"20540af3",4103:"d07ad772",4116:"cddcd4e6",4122:"5ffc8074",4224:"a16ee953",4225:"38317547",4253:"87089bce",4279:"610e7425",4324:"e806c7bf",4330:"65b8d1d1",4366:"16017aa6",4368:"56af72f6",4393:"27e787ca",4422:"18d6c9c9",4438:"7afb60b1",4474:"a7159008",4485:"59b1a96c",4513:"d3540d59",4548:"d8037f4c",4565:"7b54f5d5",4620:"05fed6b1",4664:"e4c5fdc3",4671:"1d703573",4690:"f48e2589",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",5091:"05e8cfc0",5099:"1b1927f4",5138:"b4aea2ce",5180:"366cfce3",5198:"143f7888",5235:"6fe30f11",5281:"cd699560",5282:"eec7caa6",5316:"c8bdc4df",5356:"60d99771",5362:"323a980a",5409:"38cf1c7a",5511:"fa1dd05c",5515:"cc08685c",5518:"e347e63a",5526:"96877411",5547:"565a5567",5558:"3d0eb74d",5619:"7bf967bc",5646:"612b773e",5675:"5285d58e",5738:"eb333c39",5747:"b370b50c",5761:"0fad1f8b",5762:"6c124661",5779:"85c72337",5832:"bb9fe7c3",5856:"90e0b7fd",5884:"e29eb381",5923:"27b414e3",5981:"0d7bb119",6009:"8299d165",6053:"17cca601",6086:"136c1ee9",6088:"13b4aeb1",6095:"741df2ae",6123:"a2d3d8d2",6145:"2355609d",6151:"c933a311",6158:"0fd21208",6192:"c69dda99",6209:"78619623",6219:"a91c1a62",6266:"be1f0304",6337:"a28aff23",6361:"d74b5642",6364:"d4a334ea",6408:"107b7a36",6427:"b42f5805",6473:"107d11ee",6481:"2014e4e3",6523:"8bf32d27",6537:"4a2da18c",6556:"d6b4b60c",6579:"d7067606",6599:"029c6d75",6621:"61c7d915",6628:"b94a1068",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",7042:"12d3ef9e",7045:"72be5fd7",7110:"9749ab4a",7116:"4194805f",7141:"85339969",7143:"e6858589",7200:"1520c72c",7248:"e38ecde0",7258:"f9511b3d",7321:"26662da3",7326:"673df5d6",7341:"f07f4757",7362:"766e1cc8",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",7906:"b06c439f",7924:"d589d3a7",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",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",8621:"4a07aaf0",8628:"5881f7ec",8633:"07c49ebd",8688:"4d00e03a",8703:"cb01db44",8714:"1be78505",8718:"75cc8326",8722:"64947e00",8735:"2917b31e",8798:"6cfcfcfb",8868:"f9063551",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",9097:"102de343",9127:"2b26025e",9158:"8c95fc16",9227:"7c27e34c",9249:"c329487f",9255:"0ef60658",9262:"9279cea7",9271:"7810a993",9282:"d4c8693b",9336:"5d7590c2",9439:"8f951ce3",9441:"a55b0daf",9445:"6c6ce37c",9454:"5bc7272e",9472:"4c7f7507",9581:"4f30448a",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",9949:"a1e3d512"}[e]||e)+"."+{2:"456456b5",40:"af88d16b",68:"421025a3",79:"d543f284",81:"26ba55c3",104:"cec79076",109:"2a8b80c0",152:"8214a40d",211:"6359bb26",222:"0a931b29",229:"076047b9",247:"0cf1609c",288:"b5740b86",321:"506e278f",324:"5e793aef",362:"c4f91d04",416:"85e975e8",436:"9c5c0e30",458:"545fc5e5",464:"66147a15",481:"f3319d03",501:"615ed318",514:"e92b4838",521:"78d67697",552:"29c39c4b",573:"dab6893e",629:"b4a3dfa1",630:"5590a3a2",651:"2c1da688",663:"706f9763",770:"f154556e",776:"f6d45879",835:"a5356667",862:"2d95a4c6",932:"adfcf147",958:"98272508",1027:"722571e6",1039:"367d84d2",1062:"93950472",1084:"94cb79db",1126:"f77b3a45",1133:"a44a681c",1141:"ebe7ba67",1188:"1d305f75",1190:"2bba48c9",1235:"b22f5985",1245:"c186a972",1264:"2a11f212",1289:"68048805",1308:"d204f912",1340:"41f72369",1345:"05446db0",1431:"880728de",1443:"83f4dcfb",1465:"b56bad2f",1481:"70df5a5a",1505:"19aa9fff",1538:"852637a4",1565:"e9692c43",1585:"8680fd03",1604:"ea996778",1653:"42de3ab5",1661:"9d93ba36",1674:"16b48290",1766:"e3256bf2",1774:"9b58a5d2",1776:"2d3cafaf",1886:"78fb71e5",1894:"5bf1d237",1898:"6ede392b",1930:"6554dceb",1950:"fef39a38",1968:"5cb9c150",1985:"c02372c5",2032:"2d7f009f",2076:"8b81e25b",2112:"621658df",2113:"cedacea9",2119:"60104518",2138:"d6eaf3f8",2156:"73044c16",2174:"aec3a10d",2187:"0ea91606",2207:"c0cd2084",2227:"19be7258",2230:"d38cc5d5",2235:"49c0e414",2248:"fc512c41",2275:"81c29f92",2301:"2e25c318",2347:"b6d9b713",2358:"61394c21",2369:"3179f033",2400:"ac809c54",2421:"b8330e7b",2459:"0452c424",2491:"def37f02",2589:"4ebd402a",2592:"0827e6c1",2596:"7b84c748",2600:"c76f00ef",2605:"c9ae6aa6",2634:"e0be6be1",2674:"94c47d62",2676:"9f7d2515",2720:"a481b861",2743:"b722dfb6",2784:"8ca20958",2830:"a642f64a",2858:"f26d1860",2862:"604dcbe9",2917:"52451906",2935:"4d5523d8",2952:"a8d43fe5",2958:"8f99dbe0",2960:"e0906f5a",2962:"1e16655c",2964:"702af88f",2965:"d7e67aae",2998:"3ea7f2e0",3088:"65e7903b",3126:"7218bae3",3137:"4814e7e0",3177:"993e0004",3195:"39a52354",3196:"e5fedff8",3308:"5bddb47b",3332:"2f5cd36c",3343:"0c090973",3355:"0c5693e2",3359:"d0fbb140",3382:"98695aa2",3419:"c578852e",3449:"0f60a620",3457:"24cd44b0",3460:"175c467d",3468:"5028a35e",3507:"121eed95",3576:"d158cad6",3585:"3c25cf0e",3610:"1da1a812",3613:"a63c9c7d",3642:"ab66a253",3672:"3f1db171",3693:"559a6713",3701:"6701e780",3712:"9a4dd072",3723:"2f645659",3765:"0dc24357",3781:"6e0e3185",3820:"067e7bc9",3955:"2edcb8ab",3962:"085e15ac",4e3:"d0a613b9",4017:"14428e5a",4021:"0060c15e",4032:"668f312e",4053:"81a56c02",4054:"7b8b47f6",4103:"4ed10499",4116:"b0f5a7d8",4122:"382b4640",4224:"0fbc4b46",4225:"a1b9180d",4253:"c45cefa8",4279:"22b083d8",4324:"31b41a0d",4330:"d8e12cac",4366:"a22be57e",4368:"e60a700d",4393:"b3ead152",4422:"b0c01362",4438:"1b724298",4474:"64938b3f",4485:"4b55b1e2",4513:"34df5196",4548:"aa4c87e4",4565:"ad75730f",4620:"f422f54a",4664:"5ba1ee13",4671:"6488b685",4690:"03716c7f",4716:"bbc1d3a3",4761:"79a26d94",4762:"4989b07d",4773:"efe55108",4779:"7ab18136",4780:"f5ff9c8a",4803:"eee16367",4805:"7ee75f12",4807:"39c2daf1",4827:"4fbdf0ac",4840:"b87d4ac1",4843:"d5de8cab",4876:"dcfbd033",4884:"52f7baf7",4893:"f5db31e4",4919:"74012053",4954:"f2ee3b29",4955:"f3a4b1ab",4978:"ca7ccaf8",4981:"8da00f07",5e3:"42480db1",5011:"044ba5e1",5049:"60d5e579",5091:"8fa218cc",5099:"a9a56397",5138:"e042c4be",5180:"072044f3",5198:"1d5adaec",5235:"1772048a",5281:"3152ae70",5282:"63014402",5316:"390ff8eb",5356:"ac4342ef",5362:"13853cf0",5409:"01e4fa32",5511:"c6180736",5515:"e931f2d8",5518:"0915f118",5526:"4913f2de",5547:"933d5222",5558:"2b99da9d",5619:"76cb6139",5646:"e479b012",5675:"a659173f",5738:"5a60d0b2",5747:"020852bb",5761:"8417400f",5762:"ef09a451",5779:"68dbbe79",5832:"fe26e692",5856:"db56516a",5884:"53f21514",5923:"a918f7e4",5981:"d4075bc3",6009:"45757bd5",6053:"e8423ab3",6086:"1431f6c1",6088:"40ffa096",6095:"8def9ec7",6123:"6dcfb1a2",6145:"3ad1d9e5",6151:"12e46a4a",6158:"c7e0a6a1",6192:"7bed8d0f",6209:"2a48f5b2",6219:"151c5c44",6266:"e6b63afc",6337:"d95ba250",6361:"e7db4435",6364:"a2e3b42d",6408:"ef8bab33",6427:"c207b0b2",6473:"6b209a8d",6481:"f5c34a4b",6523:"2de9f795",6537:"2de5b1b3",6556:"010a242a",6579:"0c33c4b9",6599:"903e79a5",6621:"0a2b168b",6628:"70ece279",6700:"81f00e53",6714:"ef9097a7",6729:"be719ff6",6730:"e6d3127b",6766:"d08449f0",6874:"42af0747",6894:"47ec9159",6912:"e663460d",6918:"a43926d8",6924:"79ae2a0c",6925:"cdea6839",6931:"0bf95a09",6961:"9a45cf17",6972:"6bbd747e",6981:"df346d6b",6984:"e9c65e4c",6986:"9e4db38f",7035:"757595fe",7042:"e1898768",7045:"5f11d860",7110:"ddfa782f",7116:"a49fe3a4",7141:"cf5cbbcf",7143:"58fb90f0",7200:"8a60f2ff",7248:"d9018415",7258:"606bb160",7321:"fe57afd5",7326:"a9b22576",7341:"59bdbfef",7362:"5884e667",7373:"dab0a149",7382:"eec8322d",7471:"9763be6f",7483:"e7f62cec",7492:"f50e1ffd",7542:"8c2e8f25",7544:"dfc7699e",7575:"099434fd",7591:"cb48452a",7696:"5c4bd34f",7735:"bb6063dc",7757:"0fb3b47d",7800:"d7c4e3d8",7846:"ab8670a7",7858:"f2f58bf0",7906:"a328d225",7924:"5a3a9b0b",7940:"e78cbc24",7942:"46c818e8",8023:"3d50e40d",8025:"364cf064",8028:"88754719",8042:"771a3fc1",8055:"3cc0d0de",8059:"368664ec",8060:"19fef1a9",8087:"7ccea129",8093:"35c6cfe4",8100:"e4e39654",8107:"55637c17",8112:"f6ed1648",8158:"5d3c0904",8166:"93d9c059",8173:"792b0f23",8177:"06db9245",8194:"ed70f17c",8260:"c78c4380",8267:"0f469e64",8309:"85a1f0cf",8313:"ae5ebb8e",8327:"7717f183",8350:"df1dad05",8357:"2c35a4e2",8372:"6aacba73",8401:"66024bca",8414:"5373e105",8457:"1a6cb1b3",8470:"d2fc3080",8478:"5485b326",8483:"df94e672",8526:"34de94db",8542:"ed929d1d",8548:"16595548",8581:"be8ffae5",8621:"9163f54f",8628:"9163213f",8633:"04705fa2",8688:"91ddc8d5",8703:"57683fd3",8714:"1e2a6aa3",8718:"3c8456bf",8722:"ec66addf",8735:"f9c0b568",8798:"d44b9f3a",8868:"127e931e",8873:"ea89b826",8913:"1f670d9b",8919:"8d2652ff",8933:"a92d86b1",8945:"c3c8fc60",8950:"89bcbb2f",8997:"2f73632b",9008:"56754f4a",9013:"e9ef5f63",9026:"96e2d1cb",9032:"bc0d8785",9040:"47184428",9062:"53b67792",9092:"5ea187f2",9097:"ac9aff92",9127:"2350cefd",9158:"8c929c5b",9227:"19b3c022",9249:"d022b7c1",9255:"3a0dda98",9262:"308af6f9",9271:"16409b83",9282:"2b550467",9336:"bc73a967",9439:"44fe12e6",9441:"d5861c2c",9445:"9f1a930b",9454:"980951c9",9472:"02676f01",9581:"e44fb11b",9606:"00b9b662",9624:"e6e2c4aa",9661:"ad234e4d",9717:"503f4678",9742:"336d5a20",9775:"ebfdff1a",9778:"72a6efbc",9793:"a59bfdcd",9798:"2faed412",9810:"6f4e9cfc",9828:"a07234ea",9866:"6c8a6d61",9870:"cd92088e",9949:"07ea288b"}[e]+".js",r.miniCssF=e=>{},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,a)=>Object.prototype.hasOwnProperty.call(e,a),d={},r.l=(e,a,c,f)=>{if(d[e])d[e].push(a);else{var b,t;if(void 0!==c)for(var o=document.getElementsByTagName("script"),n=0;n{b.onerror=b.onload=null,clearTimeout(l);var f=d[e];if(delete d[e],b.parentNode&&b.parentNode.removeChild(b),f&&f.forEach((e=>e(c))),a)return a(c)},l=setTimeout(u.bind(null,void 0,{type:"timeout",target:b}),12e4);b.onerror=u.bind(null,b.onerror),b.onload=u.bind(null,b.onload),t&&document.head.appendChild(b)}},r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.p="/",r.gca=function(e){return e={17518879:"8873",17896441:"8401",18100524:"1264",23794275:"1776",38317547:"4225",61595218:"9775",78619623:"6209",85339969:"7141",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",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","4dd5816e":"1604","21cde469":"1653",d8ff000f:"1661","2f36012a":"1674",e39283a8:"1766",b4657038:"1886",aa5b6080:"1894","55c77f1e":"1930","23a8ac29":"1950",c3701568:"1968","27258a7d":"1985","9000b231":"2032",common:"2076","1ea13486":"2112",cd25a595:"2113",e7ffb4b4:"2119","1a4e3797":"2138","4d049718":"2156","07666c14":"2174",dc9a99e0:"2187","1aa05129":"2207","0db959c8":"2227","8b6bafea":"2230","3d2d0a86":"2235",c275698c:"2248","5ececfab":"2275",a9125b44:"2301","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","82395e72":"3576","3f944aba":"3585","579cc8d4":"3610","22e1e32f":"3613","263ebc7a":"3642",b103c05a:"3672","5a9b411c":"3693","8d81badd":"3701",d49884c9:"3712","1428bdad":"3723","0343976d":"3765",b7442939:"3781","24aca886":"3820",aba5bf07:"3955","16565e6a":"3962",ce95b17c:"4000","9073923c":"4017","03abab96":"4021","56279b5e":"4032","78da31a1":"4053","20540af3":"4054",d07ad772:"4103",cddcd4e6:"4116","5ffc8074":"4122",a16ee953:"4224","87089bce":"4253","610e7425":"4279",e806c7bf:"4324","65b8d1d1":"4330","16017aa6":"4366","56af72f6":"4368","27e787ca":"4393","18d6c9c9":"4422","7afb60b1":"4438",a7159008:"4474","59b1a96c":"4485",d3540d59:"4513",d8037f4c:"4548","7b54f5d5":"4565","05fed6b1":"4620",e4c5fdc3:"4664","1d703573":"4671",f48e2589:"4690",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","05e8cfc0":"5091","1b1927f4":"5099",b4aea2ce:"5138","366cfce3":"5180","143f7888":"5198","6fe30f11":"5235",cd699560:"5281",eec7caa6:"5282",c8bdc4df:"5316","60d99771":"5356","323a980a":"5362","38cf1c7a":"5409",fa1dd05c:"5511",cc08685c:"5515",e347e63a:"5518","565a5567":"5547","3d0eb74d":"5558","7bf967bc":"5619","612b773e":"5646","5285d58e":"5675",eb333c39:"5738",b370b50c:"5747","0fad1f8b":"5761","6c124661":"5762","85c72337":"5779",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",a91c1a62:"6219",be1f0304:"6266",a28aff23:"6337",d74b5642:"6361",d4a334ea:"6364","107b7a36":"6408",b42f5805:"6427","107d11ee":"6473","2014e4e3":"6481","8bf32d27":"6523","4a2da18c":"6537",d6b4b60c:"6556",d7067606:"6579","029c6d75":"6599","61c7d915":"6621",b94a1068:"6628","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","12d3ef9e":"7042","72be5fd7":"7045","9749ab4a":"7110","4194805f":"7116",e6858589:"7143","1520c72c":"7200",e38ecde0:"7248",f9511b3d:"7258","26662da3":"7321","673df5d6":"7326",f07f4757:"7341","766e1cc8":"7362",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",b06c439f:"7906",d589d3a7:"7924",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","6c4340be":"8350",aebf35b6:"8357","57f5c28c":"8372",c0fa6485:"8414","509d2004":"8457","1ba75d10":"8470","2d4548df":"8478",acbaac14:"8483",b8487569:"8526",b9d6d6e5:"8542","346bcb92":"8548","935f2afb":"8581","4a07aaf0":"8621","5881f7ec":"8628","07c49ebd":"8633","4d00e03a":"8688",cb01db44:"8703","1be78505":"8714","75cc8326":"8718","64947e00":"8722","2917b31e":"8735","6cfcfcfb":"8798",f9063551:"8868",bf2a5963:"8919",f94b062c:"8933",e2e51976:"8945",ed0c0463:"8950","4a060504":"8997","24ac61c7":"9008","9d9f8394":"9013",bd2c4a98:"9026","21637dff":"9032",e5d7b215:"9040",caa79efa:"9062","2ef99682":"9092","102de343":"9097","2b26025e":"9127","8c95fc16":"9158","7c27e34c":"9227",c329487f:"9249","0ef60658":"9255","9279cea7":"9262","7810a993":"9271",d4c8693b:"9282","5d7590c2":"9336","8f951ce3":"9439",a55b0daf:"9441","6c6ce37c":"9445","5bc7272e":"9454","4c7f7507":"9472","4f30448a":"9581","5792f9ba":"9606","2e301473":"9624",cd30f404:"9661","976f6afc":"9717","820db038":"9742","9d336ee4":"9778","0370fbfb":"9793","58e6b30f":"9798","859fcda7":"9810",d6188fd4:"9828",a99e9943:"9866","7515d7ec":"9870",a1e3d512:"9949"}[e]||e,r.p+r.u(e)},(()=>{var e={5354:0,1869:0};r.f.j=(a,c)=>{var d=r.o(e,a)?e[a]:void 0;if(0!==d)if(d)c.push(d[2]);else if(/^(1869|5354)$/.test(a))e[a]=0;else{var f=new Promise(((c,f)=>d=e[a]=[c,f]));c.push(d[2]=f);var b=r.p+r.u(a),t=new Error;r.l(b,(c=>{if(r.o(e,a)&&(0!==(d=e[a])&&(e[a]=void 0),d)){var f=c&&("load"===c.type?"missing":c.type),b=c&&c.target&&c.target.src;t.message="Loading chunk "+a+" failed.\n("+f+": "+b+")",t.name="ChunkLoadError",t.type=f,t.request=b,d[1](t)}}),"chunk-"+a,a)}},r.O.j=a=>0===e[a];var a=(a,c)=>{var d,f,b=c[0],t=c[1],o=c[2],n=0;if(b.some((a=>0!==e[a]))){for(d in t)r.o(t,d)&&(r.m[d]=t[d]);if(o)var i=o(r)}for(a&&a(c);n