From e9a36ab9a7933de62d8ff24c2e265cedaae722c4 Mon Sep 17 00:00:00 2001 From: Zi Xing Date: Sat, 16 Apr 2022 18:26:46 -0400 Subject: [PATCH] Added added third-party library 'php-school/cli-menu' --- cache.db | Bin 0 -> 251191 bytes .../php-school/cli-menu/Action/ExitAction.php | 17 + .../cli-menu/Action/GoBackAction.php | 20 + .../cli-menu/Builder/CliMenuBuilder.php | 659 ++++++++ .../cli-menu/Builder/SplitItemBuilder.php | 169 ++ .../php-school/cli-menu/CHANGELOG.md | 161 ++ .../php-school/cli-menu/CliMenu.php | 786 +++++++++ .../cli-menu/Dialogue/CancellableConfirm.php | 112 ++ .../php-school/cli-menu/Dialogue/Confirm.php | 73 + .../php-school/cli-menu/Dialogue/Dialogue.php | 121 ++ .../php-school/cli-menu/Dialogue/Flash.php | 43 + .../Exception/CannotShrinkMenuException.php | 21 + .../Exception/InvalidShortcutException.php | 15 + .../Exception/InvalidTerminalException.php | 12 + .../Exception/MenuNotOpenException.php | 12 + .../ThirdParty/php-school/cli-menu/Frame.php | 47 + .../php-school/cli-menu/Input/Input.php | 32 + .../php-school/cli-menu/Input/InputIO.php | 256 +++ .../php-school/cli-menu/Input/InputResult.php | 25 + .../php-school/cli-menu/Input/Number.php | 130 ++ .../php-school/cli-menu/Input/Password.php | 131 ++ .../php-school/cli-menu/Input/Text.php | 121 ++ .../ThirdParty/php-school/cli-menu/LICENSE | 20 + .../cli-menu/MenuItem/AsciiArtItem.php | 187 +++ .../cli-menu/MenuItem/CheckboxItem.php | 172 ++ .../cli-menu/MenuItem/LineBreakItem.php | 126 ++ .../cli-menu/MenuItem/MenuItemInterface.php | 55 + .../cli-menu/MenuItem/MenuMenuItem.php | 157 ++ .../cli-menu/MenuItem/PropagatesStyles.php | 16 + .../cli-menu/MenuItem/RadioItem.php | 192 +++ .../cli-menu/MenuItem/SelectableItem.php | 132 ++ .../MenuItem/SelectableItemRenderer.php | 66 + .../cli-menu/MenuItem/SplitItem.php | 388 +++++ .../cli-menu/MenuItem/StaticItem.php | 109 ++ .../php-school/cli-menu/MenuStyle.php | 852 ++++++++++ .../ThirdParty/php-school/cli-menu/README.md | 1473 +++++++++++++++++ .../cli-menu/Style/CheckboxStyle.php | 119 ++ .../cli-menu/Style/DefaultStyle.php | 30 + .../cli-menu/Style/Exception/InvalidStyle.php | 30 + .../php-school/cli-menu/Style/ItemStyle.php | 18 + .../php-school/cli-menu/Style/Locator.php | 115 ++ .../php-school/cli-menu/Style/RadioStyle.php | 119 ++ .../cli-menu/Style/SelectableStyle.php | 112 ++ .../cli-menu/Terminal/TerminalFactory.php | 20 + .../ThirdParty/php-school/cli-menu/UPGRADE.md | 113 ++ .../php-school/cli-menu/Util/ArrayUtils.php | 41 + .../php-school/cli-menu/Util/Collection.php | 45 + .../php-school/cli-menu/Util/ColourUtil.php | 334 ++++ .../php-school/cli-menu/Util/StringUtil.php | 52 + src/ncc/autoload.php | 44 + tests/autoload.php | 7 + .../load_configuration.php | 2 + 52 files changed, 8109 insertions(+) create mode 100644 cache.db create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Action/ExitAction.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Action/GoBackAction.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Builder/CliMenuBuilder.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Builder/SplitItemBuilder.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/CHANGELOG.md create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/CliMenu.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Dialogue/CancellableConfirm.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Confirm.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Dialogue.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Flash.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Exception/CannotShrinkMenuException.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Exception/InvalidShortcutException.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Exception/InvalidTerminalException.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Exception/MenuNotOpenException.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Frame.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Input/Input.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Input/InputIO.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Input/InputResult.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Input/Number.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Input/Password.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Input/Text.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/LICENSE create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/MenuItem/AsciiArtItem.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/MenuItem/CheckboxItem.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/MenuItem/LineBreakItem.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/MenuItem/MenuItemInterface.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/MenuItem/MenuMenuItem.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/MenuItem/PropagatesStyles.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/MenuItem/RadioItem.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SelectableItem.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SelectableItemRenderer.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SplitItem.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/MenuItem/StaticItem.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/MenuStyle.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/README.md create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Style/CheckboxStyle.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Style/DefaultStyle.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Style/Exception/InvalidStyle.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Style/ItemStyle.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Style/Locator.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Style/RadioStyle.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Style/SelectableStyle.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Terminal/TerminalFactory.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/UPGRADE.md create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Util/ArrayUtils.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Util/Collection.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Util/ColourUtil.php create mode 100644 src/ncc/ThirdParty/php-school/cli-menu/Util/StringUtil.php diff --git a/cache.db b/cache.db new file mode 100644 index 0000000000000000000000000000000000000000..638b39929bea4c1fb100bc93c04f7894d409ab14 GIT binary patch literal 251191 zcmeHQU31&UlJ#%#`&~*RDN6K{qd2>+y18-L&h86dAP}SwLjVf^W2s#E@7q0t84QRa zJ}FU<&qHER1VGGSKDtkzKJ6|Sm&+gNa(=#iJGqat$^ZQN>)H8a6J+Tm^1Ml!c;eqb zvmgwzz)vT??IJG=;wb&E?cMh6yFZo}i{;y|cm5aOPn`F=EDmFL<=nX5o&O=qlE=5p z3;u!WeEIfG&1r8EKi!3yxZ#!MhM(Ld^*_sVmea#`G|qdoi>MiI-?_{4<&R)__AXss zOqXw|SK@C4(8kEmrkimYI`pW?)@}#@9B*M%k#_G^~Lq<@_fN{Al| z<$Kvp9Ib=RP7XzV))+?yFKs+BeBD$hkWJmnrg~;m^;tcKjaZtFG;HLu-0RtmHIGJs z*{J7Vh~^jP*E|+4Y5l9)WArGaO(qEa|HRpE@h)2FKaX+nO)o2hZ%u8B;%v=rGha-f z-Dk!d;Y%KEwDGs@ftNC7=V#}$%d6?7FbEnpPd7JsMl?3rq`+7!Y{HYSk37~Ei^VyQ zwKFd!-8`OmQ$(u&{I zeWx=!FQm^wi+;PItataDc;%1NrzGF3JeKvY?s1!X4rbw&zy7Vg^)*$zCdy(u75l@2rgGi>&@fRLjhx)XVMss)L6Kve zFjGPzs}qKCNypO->p5|*FmaxC;*eL{?)ANrc^2;yo^r2mo>9Yi%JrOQ*O+H7YMwPs zOZ~QA!?gU8B|)@#h0~Hi4rpZ(i2k-5edSVH&?r68Dj3@tClWz7R5IrUp3m3WS+?B+i3? z(sTdvsv*?a;9oKd^D*=9Cw!njjMDn0;6~NUWNap&<~e+zKJ>JK&j|veT?3nKvDv-m z&6f7&E`vT8B6sTX#dGr8LbRLxHwG zFTF3k+ihB9m%M=x%0hmxADVh*SGo|kciKsc|%sX7tbQ3 z0e=Ku7Z40V@Wu*fntf!xHQ1Qt8TPX;r|(lQ2;L{zD_u@qZXQu4hAgK)2~8HuDV9@- z>=<73^Dd{2Yj=4%k9O^Dpz5~87ylhZ{x6B|ejDrJJtM|jjjtb4`);{?LsoCldL_{t z2qTZ8J<$3j2qUd>&*knnE~v*eh8utEn5#EIyPXz~(e4!usnu=wiqGyUh{w85Fj`Qv zPbA#7A$tVa^4KGGVr#%2q0s!IJFrKnj07DwR0n&WQtM@Ew7bzT=DiM4l1xAzcl{#b zu44>Tb`LH0$(ub#9t-v+>`i;AVQT$#us6N1y{QM~=F~*otA=#rwl3BepP3ErZRn5H z&zh05S>tD=x`9KSE##MBL&JuK4Xw~n>A_tl##-S>WRGGO#V(3n6uao2Q!;E9rM0;80)BG;^++MYFIy66 z9;@rxU=F6-wgF!21+v1i-(tVTevAF~h3vPD2!OHVpM>UhxdR_rs^BnH{*Q^<=r zNkr|Ui0%dV3t-;+{)QSV9ugWa-dFChE}I|_Cb>?qh# zu%lo{RikQht1TlIJ?tnl)2w7!>rUR|{-?9k7Q?i|z6d+*-?8Ur@hB6krdEj?`CdcW ztiBv12w%cBgKY-e47M3;GuURMwav)(YhxpvJZw2EXI>g|MZ&!JJW9yTnusV3x*|

!wp9Sl1db};N<*uk*-ISf0p0=pO%lg+j3`Q7?Fc@Jl!eE5K=sOi8s)xZyCTUBnrN_-r7m>a`M*hWz2hZPTK^#p! zMt{3uuo|spIB)vWv3d-q*$yg@sRN{Vs+TC>Lh#glpi8*5GZM+tepthL{{bNG@=?d>eV5v&#Z5 zs^h25dKY=@Eu?SXNgfBCLY^RIikw0w?M4Fs)_E+R&huA1F{E?Az^YTLOx*%Gh@ev1bzc?(7D74;$- zW!BY+U6oPwbv@)&YIA8zQXRlZHcCzjbENPV>^q>+;H{PqfRTK+-CN0|fv1z3RS&^P zwgAB$jbyUbt>rD0VOF)!PHkK-hE*o{7;SgixBVz9$58@k#{o+1+n4?^H}!(RO|s+sm|f9W|5zAA{%zvB-;VQZ4G1aF zX2V?M9(UA>fFW)43=CWBzQ0aK~0Y=3$8PfDKt?W4? zEO%iI4oCw~{QsnUkShxA49Lxs_PO}~XFnxH`cazbRDh@on;35>5l!oBrK98ytaMoE zu+jl{1MUXzxw_FxycnDi$vo=dG*~H7vNugl0mBw;fAbf?3F!-WKarJAw{2@Fo*Z^3 z>dj!Y{;U5mN_+l-IPTSDM%wckwW+TmkD^jAp}xKPjcS(wr&h zi0b50FJAd(GOX3F_GEOqAZOZ_R8F&Xyf_RgA(ql$+nyfp627w4>6GIdM4P?St#Lg? z4GFDf0j$Yb`jvrM=|qxR(VCc=vchcN!LyTA3v zSybGr$R*!VBwE$i??CBE_#N;&;CI09fZqYX1AYhmjsx;WM#xAB9NB|x@H;9!XgCup zh|$UKpp#n|z#Sd6(}ht6reMDpte44$hai)OqYR~32|y$>N`xL#1qd>E*w?K=fmFCP zaBJY!z^#E>1Gffl4cwZFQC?xf!L4x=Ww+$8kfYF=n{|4(hMu6UX?^OT&K1Sq1_X6- zKj^>XUtI6oh&>?^%&jiaxhJ%VZ>e#Ed?AvSM4k%rRCGcCAE*z=Q-Nr#-t^RdYy8yi(ZjG-g0wp?|X z*4&();UX$+3Kt13Qpwy?A5Lb1*{uonSV-lkG)2l>)%~Fk%E|SptHJrsI{%Zn@>UyC zb)HicuRV@P1YD%h=bl6rXSp}q7d5y@h3C@V9fV>pZvck#BdkAr^uss{E)rLw6CG01 zVY$a+GO?6TX`jP2E)w~Sbtb#vwvz;c7w@9Xz2(X}|D2AZcRj3%;fDv$-!her)DHf3 z!(jC_uc)oR7^CAgx8}=LR6`U2R)5jgD?{0Ekofj2d}XM@D?{K4fva~?38)H&scE9! z<2|p~T1cYqBE9$5i`5};6@)84adbcAifg=F<-%;%L!kYxO$6;ZvCx<5>LEdJhG1+K|)MmfMAuu*bWZrs+XW`$uQ@${Jz@O>w0M6=;fieRbtRfu?Aq zw7p_)k9^4f{)OR0UJ#NQ$Pk;GY&frl>V4+1w^tQF{Bjp3nYYWv?NeI8CH=y5*@3*R z`is6UjWj<0xb{< zs1i`x%Re%@<;A(c1M4#U8n|J++4&Q7Fh;M}J{wng(;Ris*U`O%qYFn@doOTw*`X`C zLs_8536f6hBUy;ZmOEeh)_V?Q*ASxeA0f0uv;w0q5s~H0P$O&1%2St~C{j8*bB?VU z&4|eUU}x(xtdTrxU8L|O9q zCL=|~G;{B_Z{N{oeK|inpDm`-1(Tu{WJ(SQ4l9RvauY}EAh{o;!weXAc3oQk$ z&dfE`N;}Y(r~_*03El2tD#X94fb?&no8FDm>9#_b>fJbNZdYHI`wA{MTyD7B-d!A9 zDx@P6t$<$b)2ai*d1F}B8pl)TI?$Vf-W2qvEQwUo2UW|=ARpK2!N~igEM^HfI6%3i zRm@6rk$uR3m3}{UdT1&*2z6nFZk5^LaJhF*UZ&A-#3;0A)_iGATUMjZa7xQ}HNK#I z8k}p+?l`;vv~`E|Abv`hn--*2o}cl;+Y^^h=g(i0`2SJD=x*fsVaQdIMjTO})ekum zm{yG(7+k-Grw>mbo<2N%9YE`z77R}x+0{m-MiHH5?+7wrkO9*!pLCib17=gt0qGp1 zb6wpPo_>u#{#4o3tDW?38-VUlj$4!tP+S{ zk(1yMY<0bt*_g;7VYedKv2{Y2n4E_k(0@8rEoNXK&T#oIJ^!#>Ml_SNK`QAOcj&q z&H~Zo$NHoXh{FdgcIW7RsAT!u3;5-ysS#bd%ARW@Ap&UTK{F4D3YJ70Bb8rRpe1sO@`gFw(_ zz5L*l;}`AoF!nhUA0vWazhsH;j#9;t?XFtfLM-k?0HF5u#VaTz4!i<*h3R`Kj}(jv z;1$Zd17o71{HCUf?wT@!1H2;ik!~U24zV|bF+sd5iT)tn;;^R<#snA>V!Z%k0*r~L z6jpfgjEP}*1zp|Adp1}n=frI!%Y|6|apG<^M64HC0naQg$rO&+_4T!&aI}|}+=oCu z1zSIz{2y@|;_s>WFiHjobwDi=vgKwv-(@q!hrWQw6o3fyC$vuo0tdUfMRzD}H+y!a zJg4sNF0;r{^l*45&a7&18l9k2wXMrLSSp+^U1W$hNNd1QUsz6jIKp#ULp%EC)PaGb z=*T7r9Cb>5iiiOMM?opz#lno!-Mv5EtZ*1jneabP4Jkspot#&>G76UA%03X;zRBj@V z56F2y&V$E8d4yC`N9>shY9yiRhhqHd9#IFtVvKqyIh8|sYrLIR`Q*T2a*hYj!o0_T z#c1YB!Kn`-p*N-nl~y}G=;Q&50T$zs)LRfoq(~QJ@{sKy2@cx{X88r1_}2Bl?O$?X z4IQBBhn$*sagvetfu6G^^zYy_1r`G=M(SDGL?zT@Jvuq%WLOOSa4$r_M1d#_+=AU9 z&>zDjJpmy{YpT!__tjJpFpz+MK1Sr-uU*d{B_*flOX~#$%>e`f2r9ez%0~qdge)aw zDN(h!UJR`67by#-0aVjul#|WRSv|R|Om9L_7!-xktBB+XAxp^ya7sD~vXqdege;|H zZIM<0K>&gP1eHs?*r*{#0D{Q)?T1E4WA^#!L^`pHSWJU(q(7tJVZ2l#YJCgbZ%1tu z*k9k2u1latK#zbPp`@@5vUi6)n8Z+@h9vyOMdr+y{{xI_iL;n535Q$d8b- zQLOYhphrwsMM@V^x_(FjaL|aLans-fgGQtZ1iwu5NJd_};TR_7)r&oKLhjS$0PfS> z_LF>>V`MzBT1owDzT4(StotHW3m{cMs(@4hsnX6jkgB67O?B@^?a0=ne&9KwdQ|op z`VJD_%B!|S<#h6ls;^Up{|>sqK&muW1o0sxyb*G!XHyC4y`V69o=)l}8&*g#bJhr! zZ>gM=BH>MC!rRL(O|6)=K6f3u>0Rl~Oy{KMc7LvlmC}ASugl zcKRiXqSX7b(nsHAL1@ZFHUbqus(@6b&c0ZalzFWma0YN>qMTH(?J{}MOXb` z6=8%Hl!5v5Oypzyr;(l`_+$GjQu-})PDV4Ix)B?-ao3nJ-}umjp)u;2?ih{imD8bW zSENkX8&&iCEvqC>{vB@u@54j>ag3C+Idww=x|X-j3AwRGfQa86Ey^7g*RO%H0c8Wq z29ym1Gzzq49Bx%u~VploS*VU-*)2yNL|B1n})s$?WKAVCjm$>CD@xP~KO zxT)l98efoy!2U%wVOyW$5bG$4v-B*PzpS~Ob!xo2YP zCB=iOmN8ii6x48-7){qulHgmvLNuR>|n7*fPu(-Mi_UUO3q=>v%_HCDnVczsm(pBEE}av8GPqZ~TX? zn*kRDE?9P76~hedJFxE{!0&EojZX!nL)$@aDps8#J!v4oFX6Af#8I&Cz`g_fuCNuS zVBZ;zJ6XLRS+l?empUAGFn=5Z{1D)W0DqZ>2wc$13N87U&AyZ2nOekKgBlh3*R$Y) z>GBAGl(DbIVvbUN2{t6GJ9eD1J#R6`Dbu{!<_qn^ zV59*Fq|#3!6Okoyav9Rpo$SRc-#nA%U)5vJMKKJM+!{4zRG1>1A@imPwQYNPyi54X zR;Q;K1)?{5r;|xseP)d^@PYckzi|>VdAlyUdMqc+2w4ez zFJTfu)xcOM?!5@`>oEzWQdz;eOAby`AeBHWfm8yiOdWwuYVr|~%Dp`L!WPm;hQCq6 zV0>9fB|XhC05Zb@92;_~`JL1cgZZ5wBSA5IpNrpqP)xs3GCbQ4j9Sg#?z!KW1dV~? z3FMSe9fr^ZvZFv9AgADXg5wE}CpezY%3r&?Fsp)aEwMI=WZ1(&675p~nnCxsQs(6S zQ6?A2>2{YTeoBM500J*4MqEYpWDYutj{rGE?zaqg>QruZP)s4@ewVYOR1Z1oKqiGW zWiaM^ASQVj%oIk*YngDgcpc8Kg~Fl%74^*E&J%j-UjlN!UtR7ukW&RGIu_1pCnWbU zU}x~sj*`XSpvb~=nezPWwILIK<$IwkbFlSN%6mjF)?& z;4muiw?yA-oorS9 z(m$sTjK--4W!;i0^r9|sz>Wnw7VKEd43T)Y=7E46%S#6J0-?L||G;>4R|x3IULzOm zSm=8;0+)KPw(jx@;Do-XEC$4;S3ORM0@IT2YfHyxqqh<5wp|E}x32zD9#<$?`W*^P z(@SYiPWQc?P-a;Nq&Jupp`n+q?+J|e^v9j zFis-0py1={W6*^^$=&BGq13BCc9}+##|R>K=aDlwzlwK6>d2)uWLUO4lsp5J3`y7m zJ7w=vfmXcpL1@AIb{i9O$iFYy9KF!R22}?@$pZUO!%q)NV>bhod=Dsj2Phd(GN5D= zB(6b50VV5{7o#g`It)-UpkzSFK35I%{4iv+U}(iFK*_=KjPuTVA;N%?4M5l}XiFEk9G28A9fhE2q_V?C1>n!(Tv zrofmi?!CX_Eqama&Wq%Cz!)Ihe6 zPckR&1FB=;r~}H<%i`pb9|6_Pj9#z~SOabjV&i110=_(%g73GIa;8~37uNhE z+8EA}NwfdZ3xD;%tFON>Q^4GMQ4m+#A?4Td9d5TgT>t`$ijA`KB~KD?A>`BZL{U;Hgu$ za7XB_DfbA#_0Z?;NqiPAG^Go{Q!f~z5)f7~yebad67B_0ot7wo>$bEGgPaZZZm4%# zYhP#tf^{~)Q{NAxYcXzhVB}9gz5CA0cu+lr3XK5Qmp^j6ryf5Nswn{14>5+rcoTSf zfiC&v$05f@OYI*8M2G`T2i3UriUcLZVOKW~|lhpq#Dz?8lVpYzI>$BPAIcv`>Xo%DS z?tk3=<$GB=`IN+ba1%%CV6&5zK_|a(DthTpV+7~tw1hG`AIqllI>}8H`gN+Qj>x(% z{i!dKe+48TNWKOm#Q~6f)dNtR(MjpLOVoj}U(v!1#hLxs29SIp`6Wddva_o4IY9E4 zS|+4@)M92$Bmt6d8(~25^&Vz)1r%pY{8c;rK=N%<$O2F6lr|vwK=M6L;X0tn`w0oG zQBr}LAZ!K$$wwW|hEY)LKo)6^PPFuVDgwzTM;%ChFLiu_z&bGaacU%=qBniv9HL%%-e{ zsJer?jE&PuRz?04j_#mlDtASBELKwmW>yNK?nJWswl1eLrve2`4F`ml)0*B-eX0$X zafPtsyzK5HM0rXLArz?NKph9_IF_jl*x$Cm8CW+6{2=gKch3TJ0fFDLumJXFdR<`$#2m&1*n{!%*YX?%XBJY#ykB&)#z<*!WY%2PHXcz+OID0}( zd0gfxYo`8`>Nqw6|6tf(?%f?w=+i_CF0L2zGf}j*NkhLmabS$0f+<-_jW0>$3iON< zET}|Uy1bxmi+_ggv>*%o)LHK$FAL(xu-Yz2qQ897-)ZS zCCfpdRf1p%Of|m9smJ`o`mgkOlv73t$?JGWDiTF9lL6#b?!xjCd>8kYOhYOWmpY_B zq}7Zu2>n3lCx`{AU)uPQ9Bv@Bmvup|Ma2$4o;beE_Dh!CNiKnY+_1H&ojb)cMptn)X82$53!7coaf8TM*_%Wwdq z3_4>Vhz%=;sKr%uTy_~*EVr^;iB1+A5|$wb3fW`CX$dlUXgq~=4(Ata;#=4Iwtoo| zc&ZP+PTYH;)S;i4%rcKSGlEww;{inKsa~i}QN`XNiVRiup{j)KxHgC~Fz9u-Shv-p zN0b5C2-3esHbRxSEh8)9|AtSXyjh44*)nC2jj&g-S#Mv?Q1(Bf42Uue3~L$W+Miv7 zsAo0;fu0@s@p`Z53VF*5pEo=)yS_ZTo-gJcp17n&_6|>clDzvdCO>eZCo}eIV-tB^ zLEpdx@!JuYKw!cISrx*_4mr{vkp95qp`0L76)!^i1F9paH3WePDcHlaB!}NQJZ%Lv z<(W#2Z3tLDwW@&0`-idTW^rO5tk&?fJh^y%gC57q3zoltz=RERMqq;X86#T*fe8dA ztT5G#{K2}eVS|N|qhsQwX~2uuJ{<)@V1nK1S$!0S6tg@(3>jAyb@(8Y1ev7Rq9}vF zMD$1uLrc#f{Q>C@ia=mVNHEZqqu}2cWO5%CWugUt;I9}PD7g>WT@rui%|RfK-Sbl* zlSDotRe7sbOUt8dW#fe$NpdZzBygO#n+=J$2n8B?zw`ye#q?j{=_x^)S`7I`q(6{B z(l0PU7j^>5PZZ8LpH1gyBAh|9r*}BxhBg|~{z*m|&uEj1!#gQAux~(Pihu_6oXT)D z0vf6ZkZFNT3nFHAFX6y&ffdo!BTF4v$Y~A1A=G_9-3QctuppW;TB0FL_J?Iu}NdOv|7S$XS1T+xPP*x}c8lEp?C7m3k zM?eDsjl2?p_NSgRpg}uZH+=mRagh1h+4OwA5UNv`6t(Fa2N`4dgT3UYbdJ7Jj~SvK zhakquOlqGb9G>)7YIk$$!Dlt73 zTGL;YKyX4VjW1}QhQ1W^r6^t^y+uSl5cSA0NEx-L#4Zr^*waDMylU + */ +class ExitAction +{ + public function __invoke(CliMenu $menu) : void + { + $menu->close(); + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Action/GoBackAction.php b/src/ncc/ThirdParty/php-school/cli-menu/Action/GoBackAction.php new file mode 100644 index 0000000..3844d5c --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Action/GoBackAction.php @@ -0,0 +1,20 @@ + + */ +class GoBackAction +{ + public function __invoke(CliMenu $menu) : void + { + if ($parent = $menu->getParent()) { + $menu->closeThis(); + $parent->open(); + } + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Builder/CliMenuBuilder.php b/src/ncc/ThirdParty/php-school/cli-menu/Builder/CliMenuBuilder.php new file mode 100644 index 0000000..f73e732 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Builder/CliMenuBuilder.php @@ -0,0 +1,659 @@ + + * @author Aydin Hassan + */ +class CliMenuBuilder +{ + /** + * @var CliMenu + */ + private $menu; + + /** + * @var string + */ + private $goBackButtonText = 'Go Back'; + + /** + * @var string + */ + private $exitButtonText = 'Exit'; + + /** + * @var MenuStyle + */ + private $style; + + /** + * @var Terminal + */ + private $terminal; + + /** + * @var bool + */ + private $disableDefaultItems = false; + + /** + * @var bool + */ + private $disabled = false; + + /** + * Whether or not to auto create keyboard shortcuts for items + * when they contain square brackets. Eg: [M]y item + * + * @var bool + */ + private $autoShortcuts = false; + + /** + * Regex to auto match for shortcuts defaults to looking + * for a single character encased in square brackets + * + * @var string + */ + private $autoShortcutsRegex = '/\[(.)\]/'; + + /** + * @var array + */ + private $extraItemStyles = []; + + /** + * @var bool + */ + private $subMenu = false; + + public function __construct(Terminal $terminal = null) + { + $this->terminal = $terminal ?? TerminalFactory::fromSystem(); + $this->style = new MenuStyle($this->terminal); + $this->menu = new CliMenu(null, [], $this->terminal, $this->style); + } + + public static function newSubMenu(Terminal $terminal) : self + { + $instance = new self($terminal); + $instance->subMenu = true; + + return $instance; + } + + public function setTitle(string $title) : self + { + $this->menu->setTitle($title); + + return $this; + } + + public function addMenuItem(MenuItemInterface $item) : self + { + $this->menu->addItem($item); + + $this->processItemShortcut($item); + + return $this; + } + + public function addItem( + string $text, + callable $itemCallable, + bool $showItemExtra = false, + bool $disabled = false + ) : self { + $this->addMenuItem(new SelectableItem($text, $itemCallable, $showItemExtra, $disabled)); + + return $this; + } + + public function addItems(array $items) : self + { + foreach ($items as $item) { + $this->addItem(...$item); + } + + return $this; + } + + public function addCheckboxItem( + string $text, + callable $itemCallable, + bool $showItemExtra = false, + bool $disabled = false + ) : self { + $this->addMenuItem(new CheckboxItem($text, $itemCallable, $showItemExtra, $disabled)); + + return $this; + } + + public function addCheckboxItems(array $items): self + { + foreach ($items as $item) { + $this->addCheckboxItem(...$item); + } + + return $this; + } + + public function addRadioItem( + string $text, + callable $itemCallable, + bool $showItemExtra = false, + bool $disabled = false + ) : self { + $this->addMenuItem(new RadioItem($text, $itemCallable, $showItemExtra, $disabled)); + + return $this; + } + + public function addRadioItems(array $items): self + { + foreach ($items as $item) { + $this->addRadioItem(...$item); + } + + return $this; + } + + public function addStaticItem(string $text) : self + { + $this->addMenuItem(new StaticItem($text)); + + return $this; + } + + public function addLineBreak(string $breakChar = ' ', int $lines = 1) : self + { + $this->addMenuItem(new LineBreakItem($breakChar, $lines)); + + return $this; + } + + public function addAsciiArt(string $art, string $position = AsciiArtItem::POSITION_CENTER, string $alt = '') : self + { + $this->addMenuItem(new AsciiArtItem($art, $position, $alt)); + + return $this; + } + + public function addSubMenu(string $text, \Closure $callback) : self + { + $builder = self::newSubMenu($this->terminal); + + if ($this->autoShortcuts) { + $builder->enableAutoShortcuts($this->autoShortcutsRegex); + } + + each($this->extraItemStyles, function (int $i, array $extraItemStyle) use ($builder) { + $builder->registerItemStyle($extraItemStyle['class'], $extraItemStyle['style']); + }); + + $callback($builder); + + $menu = $builder->build(); + $menu->setParent($this->menu); + + $this->menu->addItem($item = new MenuMenuItem( + $text, + $menu, + $builder->isMenuDisabled() + )); + + $this->processItemShortcut($item); + + return $this; + } + + public function addSubMenuFromBuilder(string $text, CliMenuBuilder $builder) : self + { + $menu = $builder->build(); + $menu->setParent($this->menu); + + $this->menu->addItem($item = new MenuMenuItem( + $text, + $menu, + $builder->isMenuDisabled() + )); + + $this->processItemShortcut($item); + + return $this; + } + + public function enableAutoShortcuts(string $regex = null) : self + { + $this->autoShortcuts = true; + + if (null !== $regex) { + $this->autoShortcutsRegex = $regex; + } + + return $this; + } + + private function extractShortcut(string $title) : ?string + { + preg_match($this->autoShortcutsRegex, $title, $match); + + if (!isset($match[1])) { + return null; + } + + if (mb_strlen($match[1]) > 1) { + throw InvalidShortcutException::fromShortcut($match[1]); + } + + return isset($match[1]) ? strtolower($match[1]) : null; + } + + private function processItemShortcut(MenuItemInterface $item) : void + { + $this->processIndividualShortcut($item, function (CliMenu $menu) use ($item) { + $menu->executeAsSelected($item); + }); + } + + private function processSplitItemShortcuts(SplitItem $splitItem) : void + { + foreach ($splitItem->getItems() as $item) { + $this->processIndividualShortcut($item, function (CliMenu $menu) use ($splitItem, $item) { + $current = $splitItem->getSelectedItemIndex(); + + $splitItem->setSelectedItemIndex( + (int) array_search($item, $splitItem->getItems(), true) + ); + + $menu->executeAsSelected($splitItem); + + if ($current !== null) { + $splitItem->setSelectedItemIndex($current); + } + }); + } + } + + private function processIndividualShortcut(MenuItemInterface $item, callable $callback) : void + { + if (!$this->autoShortcuts) { + return; + } + + if ($shortcut = $this->extractShortcut($item->getText())) { + $this->menu->addCustomControlMapping( + $shortcut, + $callback + ); + } + } + + public function addSplitItem(\Closure $callback) : self + { + $builder = new SplitItemBuilder($this->menu); + + if ($this->autoShortcuts) { + $builder->enableAutoShortcuts($this->autoShortcutsRegex); + } + + each($this->extraItemStyles, function (int $i, array $extraItemStyle) use ($builder) { + $builder->registerItemStyle($extraItemStyle['class'], $extraItemStyle['style']); + }); + + $callback($builder); + + $this->menu->addItem($splitItem = $builder->build()); + + $this->processSplitItemShortcuts($splitItem); + + return $this; + } + + /** + * Disable a submenu + * + * @throws \InvalidArgumentException + */ + public function disableMenu() : self + { + if (!$this->subMenu) { + throw new \InvalidArgumentException( + 'You can\'t disable the root menu' + ); + } + + $this->disabled = true; + + return $this; + } + + public function isMenuDisabled() : bool + { + return $this->disabled; + } + + public function setGoBackButtonText(string $goBackButtonTest) : self + { + $this->goBackButtonText = $goBackButtonTest; + + return $this; + } + + public function setExitButtonText(string $exitButtonText) : self + { + $this->exitButtonText = $exitButtonText; + + return $this; + } + + public function setBackgroundColour(string $colour, string $fallback = null) : self + { + $this->style->setBg($colour, $fallback); + + return $this; + } + + public function setForegroundColour(string $colour, string $fallback = null) : self + { + $this->style->setFg($colour, $fallback); + + return $this; + } + + public function setWidth(int $width) : self + { + $this->style->setWidth($width); + + return $this; + } + + public function setPadding(int $topBottom, int $leftRight = null) : self + { + $this->style->setPadding($topBottom, $leftRight); + + return $this; + } + + public function setPaddingTopBottom(int $topBottom) : self + { + $this->style->setPaddingTopBottom($topBottom); + + return $this; + } + + public function setPaddingLeftRight(int $leftRight) : self + { + $this->style->setPaddingLeftRight($leftRight); + + return $this; + } + + public function setMarginAuto() : self + { + $this->style->setMarginAuto(); + + return $this; + } + + public function setMargin(int $margin) : self + { + $this->style->setMargin($margin); + + return $this; + } + + public function setItemExtra(string $extra) : self + { + $this->style->setItemExtra($extra); + $this->getSelectableStyle()->setItemExtra($extra); + + // if we customise item extra, it means we most likely want to display it + $this->displayExtra(); + + return $this; + } + + public function setTitleSeparator(string $separator) : self + { + $this->style->setTitleSeparator($separator); + + return $this; + } + + /** + * @param int|string|null $right + * @param int|string|null $bottom + * @param int|string|null $left + */ + public function setBorder(int $top, $right = null, $bottom = null, $left = null, string $colour = null) : self + { + $this->style->setBorder($top, $right, $bottom, $left, $colour); + + return $this; + } + + public function setBorderTopWidth(int $width) : self + { + $this->style->setBorderTopWidth($width); + + return $this; + } + + public function setBorderRightWidth(int $width) : self + { + $this->style->setBorderRightWidth($width); + + return $this; + } + + public function setBorderBottomWidth(int $width) : self + { + $this->style->setBorderBottomWidth($width); + + return $this; + } + + public function setBorderLeftWidth(int $width) : self + { + $this->style->setBorderLeftWidth($width); + + return $this; + } + + public function setBorderColour(string $colour, string $fallback = null) : self + { + $this->style->setBorderColour($colour, $fallback); + + return $this; + } + + public function getStyle() : MenuStyle + { + return $this->style; + } + + public function getTerminal() : Terminal + { + return $this->terminal; + } + + private function getDefaultItems() : array + { + $actions = []; + if ($this->subMenu) { + $actions[] = new SelectableItem($this->goBackButtonText, new GoBackAction); + } + + $actions[] = new SelectableItem($this->exitButtonText, new ExitAction); + return $actions; + } + + public function disableDefaultItems() : self + { + $this->disableDefaultItems = true; + + return $this; + } + + public function displayExtra() : self + { + $this->style->setDisplaysExtra(true); + $this->getSelectableStyle()->setDisplaysExtra(true); + $this->getCheckboxStyle()->setDisplaysExtra(true); + $this->getRadioStyle()->setDisplaysExtra(true); + + return $this; + } + + private function itemsHaveExtra(array $items) : bool + { + return !empty(array_filter($items, function (MenuItemInterface $item) { + return $item->showsItemExtra(); + })); + } + + public function build() : CliMenu + { + if (!$this->disableDefaultItems) { + $this->menu->addItems($this->getDefaultItems()); + } + + if (!$this->style->getDisplaysExtra()) { + $this->style->setDisplaysExtra($this->itemsHaveExtra($this->menu->getItems())); + } + + if (!$this->subMenu) { + $this->menu->propagateStyles(); + } + + return $this->menu; + } + + public function getDefaultStyle() : DefaultStyle + { + $style = $this->menu->getItemStyle(DefaultStyle::class); + assert($style instanceof DefaultStyle); + return $style; + } + + public function setDefaultStyle(DefaultStyle $style) : self + { + $this->menu->setItemStyle($style, DefaultStyle::class); + + return $this; + } + + public function modifyDefaultStyle(callable $itemCallable) : self + { + $itemCallable($this->getDefaultStyle()); + + return $this; + } + + public function getSelectableStyle() : SelectableStyle + { + $style = $this->menu->getItemStyle(SelectableStyle::class); + assert($style instanceof SelectableStyle); + return $style; + } + + public function setSelectableStyle(SelectableStyle $style) : self + { + $this->menu->setItemStyle($style, SelectableStyle::class); + + return $this; + } + + public function modifySelectableStyle(callable $itemCallable) : self + { + $itemCallable($this->getSelectableStyle()); + + return $this; + } + + public function getCheckboxStyle() : CheckboxStyle + { + $style = $this->menu->getItemStyle(CheckboxStyle::class); + assert($style instanceof CheckboxStyle); + return $style; + } + + public function setCheckboxStyle(CheckboxStyle $style) : self + { + $this->menu->setItemStyle($style, CheckboxStyle::class); + + return $this; + } + + public function modifyCheckboxStyle(callable $itemCallable) : self + { + $itemCallable($this->getCheckboxStyle()); + + return $this; + } + + public function getRadioStyle() : RadioStyle + { + $style = $this->menu->getItemStyle(RadioStyle::class); + assert($style instanceof RadioStyle); + return $style; + } + + public function setRadioStyle(RadioStyle $style) : self + { + $this->menu->setItemStyle($style, RadioItem::class); + + return $this; + } + + public function modifyRadioStyle(callable $itemCallable) : self + { + $itemCallable($this->getRadioStyle()); + + return $this; + } + + public function modifyStyle(string $styleClass, callable $itemCallable) : self + { + $itemCallable($this->menu->getItemStyle($styleClass)); + + return $this; + } + + public function registerItemStyle(string $itemClass, ItemStyle $itemStyle) : self + { + $this->menu->getStyleLocator() + ->registerItemStyle($itemClass, $itemStyle); + + $this->extraItemStyles[] = ['class' => $itemClass, 'style' => $itemStyle]; + + return $this; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Builder/SplitItemBuilder.php b/src/ncc/ThirdParty/php-school/cli-menu/Builder/SplitItemBuilder.php new file mode 100644 index 0000000..51d9de4 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Builder/SplitItemBuilder.php @@ -0,0 +1,169 @@ + + */ +class SplitItemBuilder +{ + /** + * @var CliMenu + */ + private $menu; + + /** + * @var SplitItem + */ + private $splitItem; + + /** + * Whether or not to auto create keyboard shortcuts for items + * when they contain square brackets. Eg: [M]y item + * + * @var bool + */ + private $autoShortcuts = false; + + /** + * Regex to auto match for shortcuts defaults to looking + * for a single character encased in square brackets + * + * @var string + */ + private $autoShortcutsRegex = '/\[(.)\]/'; + + /** + * @var array + */ + private $extraItemStyles = []; + + public function __construct(CliMenu $menu) + { + $this->menu = $menu; + $this->splitItem = new SplitItem(); + } + + public function addItem( + string $text, + callable $itemCallable, + bool $showItemExtra = false, + bool $disabled = false + ) : self { + $this->splitItem->addItem(new SelectableItem($text, $itemCallable, $showItemExtra, $disabled)); + + return $this; + } + + public function addCheckboxItem( + string $text, + callable $itemCallable, + bool $showItemExtra = false, + bool $disabled = false + ) : self { + $this->splitItem->addItem(new CheckboxItem($text, $itemCallable, $showItemExtra, $disabled)); + + return $this; + } + + public function addRadioItem( + string $text, + callable $itemCallable, + bool $showItemExtra = false, + bool $disabled = false + ) : self { + $this->splitItem->addItem(new RadioItem($text, $itemCallable, $showItemExtra, $disabled)); + + return $this; + } + + public function addStaticItem(string $text) : self + { + $this->splitItem->addItem(new StaticItem($text)); + + return $this; + } + + public function addLineBreak(string $breakChar = ' ', int $lines = 1) : self + { + $this->splitItem->addItem(new LineBreakItem($breakChar, $lines)); + + return $this; + } + + public function addSubMenu(string $text, \Closure $callback) : self + { + $builder = CliMenuBuilder::newSubMenu($this->menu->getTerminal()); + + if ($this->autoShortcuts) { + $builder->enableAutoShortcuts($this->autoShortcutsRegex); + } + + each($this->extraItemStyles, function (int $i, array $extraItemStyle) use ($builder) { + $builder->registerItemStyle($extraItemStyle['class'], $extraItemStyle['style']); + }); + + $callback($builder); + + $menu = $builder->build(); + $menu->setParent($this->menu); + + $this->splitItem->addItem(new MenuMenuItem( + $text, + $menu, + $builder->isMenuDisabled() + )); + + return $this; + } + + public function addMenuItem(MenuItemInterface $item) : self + { + $this->splitItem->addItem($item); + + return $this; + } + + public function setGutter(int $gutter) : self + { + $this->splitItem->setGutter($gutter); + + return $this; + } + + public function enableAutoShortcuts(string $regex = null) : self + { + $this->autoShortcuts = true; + + if (null !== $regex) { + $this->autoShortcutsRegex = $regex; + } + + return $this; + } + + public function registerItemStyle(string $itemClass, ItemStyle $itemStyle) : self + { + $this->extraItemStyles[] = ['class' => $itemClass, 'style' => $itemStyle]; + + return $this; + } + + public function build() : SplitItem + { + return $this->splitItem; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/CHANGELOG.md b/src/ncc/ThirdParty/php-school/cli-menu/CHANGELOG.md new file mode 100644 index 0000000..842b483 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/CHANGELOG.md @@ -0,0 +1,161 @@ +# Change Log +All notable changes to this project will be documented in this file. +Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) principles. + +## [Unreleased][unreleased] +### Added + +### Changed + +### Fixed + +### Removed + +## [4.3.0] +### Fixed + - PHP 8.1 Support (#252, #249) + +### Added + - declare(strict_types=1) everywhere + +## [4.2.0] +### Added + - Yes/no confirmation dialogue (#248) + - Ability to add multiple checkbox and radio items (#241) + +## [4.1.0] +### Added + - Ability to modify password length for password input (#235) + - Improve the formatting of disabled menu items in different terminals (#236) + - Support for PHP8 (#240) + +## [4.0.0] +### Added + - Add PHP 7.4 support (#183) + - CheckboxItem & RadioItem (#186, #189, #193, #194, #226) + - Ability to force display extra (#187) + - Individual style objects for each item type (#211, #212, #213, #214, #216, #230) + - Method getStyle() to interface PhpSchool\CliMenu\MenuItem\MenuItemInterface + +### Fixed + - Fixed item extra rendering outside of menu (#66, £184, #187) + - Fix unresponsive menu upon closing and reopening (#198) + - Menu styles incorrectly propagating to submenus (#201, #210) + - Various issues with the menu width, when the terminal was too small (#223, #220, #219) + +### Removed + - Remove rebinding $this in builder closures so we can access the real $this (#191, #192, #196) + - Marker methods from PhpSchool\CliMenu\MenuStyle: + #getSelectedMarker() + #setSelectedMarker() + #getUnselectedMarker() + #setUnselectedMarker() + #getMarker() + - PhpSchool\CliMenu\MenuItem\SelectableTrait + - Marker methods from PhpSchool\CliMenu\Builder\CliMenuBuilder: + #setUnselectedMarker() + #setSelectedMarker() + +## [3.2.0] +### Added + - Allow ESC key to "cancel" editing an input (#174) + - Methods for disabling the default VIM mappings and setting your own (#172) + - Ability to set custom validator on Text and Number inputs (#177) + - Ability to turn on automatic item shortcuts (#176) + +## [3.1.0] +### Changed + - Update dependencies + fix some static analysis issues + +## [3.0.0] +### Changed + - Optimise redrawing to reduce flickering (#83) + - Use parent menu terminal when creating sub menus to reduce object graph (#94) + - Do not print right margin. Causes menu to wrap even when row fits in terminal (#116) + - CliMenu throws a \RuntimeException if it is opened with no items added (#146, #130) + - Sub Menus are configured via closures (#155) + - Remove restriction of 1 character length for markers (#141) + - Remove the mandatory space after markers for now they can be of any length (#154) + +### Added + - Added type hints everywhere (#79) + - Added phpstan to the travis build (#79) + - Input dialogue system for prompting users. Comes with text, number and password inputs (#81) + - Added ability to pass already prepared CliMenuBuilder instance to CliMenuBuilder#addSubMenuFromBuilder (#85, 155) + - Added CliMenu#addItems & CliMenu#setItems to add multiple items and replace them (#86) + - Added custom control mapping - link any key to a callable to immediately execute it (#87) + - Added MenuMenuItem#getSubMenu (#92) + - Added alternate text to AsciiArtItem to display if the ascii art is too large for the current terminal (#93) + - Added the ability to pass existing MenuStyle instance to dialogues and inputs for consistent themes and reduced object graph (#99) + - Added CSS like borders (#100) + - Added option to auto center menu with CliMenuBuilder#setMarginAuto (#103) + - Added option to auto center menu with CliMenuBuilder#setMarginAuto (#103) + - Added support for 256 colours with automatic and manual fallback to 8 colours (#104) + - Added clear option to CliMenu#redraw useful for when reducing the terminal width (#117) + - Added ability to set top/bottom and left/right padding independently (#121) + - Added a new Split Item item type which allows displaying multiple items on one line (#127) + - Added setText methods to various items so they can be modified at runtime (#153) + - Added MenuStyle#hasChangedFromDefaults to check if a MenuStyle has been modified (#149) + - Added CliMenu#setTitle and CliMenu#setStyle (#155) + - Added CliMenuBuilder#getStyle to get the current style object for the menu + +### Fixed + - Fixed sub menu go back button freezing menu (#88) + - Fixed centering ascii art items with trailing white space (#102) + - Enable cursor when exiting menu (#110) + - Fixed (#71) - changed padding calculation when row too long to stop php notices (#112) + - Fixed wordwrap helper (#134) + - Fixed selected item issues when adding/setting/removing items (#156) + - Fix infinite loop when no selectable items in menu (#159, #144) + +### Removed + - Dropped PHP 5.x and PHP 7.0 support (#79) + - Removed the Terminal namespace which has been migrated to php-school/terminal (#81) + - Removed MenuStyle::getDefaultStyleValues (#149) + - Removed CliMenuBuilder#setTerminal (#149) + - Removed CliMenuBuilder#getSubMenu (#155) + - Removed CliMenuBuilder#getMenuStyle (#155) + - Removed CliMenuBuilder#end (#155) + +## [2.1.0] +### Changed + - Use new static for submenu to allow subclassing (#68) + +### Added + - Add emacs style up/down shortcuts ctrl+n and ctrl+p (#67) + +## [2.0.2] +### Fixed + - Don't output ascii art if the terminal width is too small (#63) + +## [2.0.1] +### Fixed + - Reset array keys after removing an item from the menu (#61) + +## [2.0.0] +### Fixed + - PHPUnit deprecations - updated to createMock() + +### Changed + - Require ext-posix (#50) + - Make MenuStyle easier to construct by only allowing changes to be made via setters (#45) + +### Added + - Added getStyle() to CliMenu to get access to the style object from the menu itself (#42) + - Added redraw method to CliMenu which can redraw the menu immediately with any style changes. See + examples/crazy-redraw.php for an example (#43) + - Added tests for child menu style inheritance (#44) + - Add getter getItems() to get all items from the menu (#46) + - Add method removeItem(ItemInterface $item) to remove an item from the menu (#46) + - Ability to toggle item extra while the menu is open - see examples/toggle-item-extra.php (#46) + - Added dialogues flash and confirm - they both display some text on top of the menu, flash is dismissed with + any key press where the confirm requires enter to be pressed on the provided button. + See examples/confirm.php and examples/flash.php (#49) + +### Removed + - Removed windows terminal - many required terminal features are unavailable (#50) + - Individual component instantiation restrictions (#41) + + ## [1.2.0] + ### Added + - Added ability to disable menu items and sub-menus, they will appear dimmed and will be un-selectable (#40) diff --git a/src/ncc/ThirdParty/php-school/cli-menu/CliMenu.php b/src/ncc/ThirdParty/php-school/cli-menu/CliMenu.php new file mode 100644 index 0000000..fa3f1c3 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/CliMenu.php @@ -0,0 +1,786 @@ + + */ +class CliMenu +{ + /** + * @var Terminal + */ + protected $terminal; + + /** + * @var MenuStyle + */ + protected $style; + + /** + * @var Locator + */ + private $itemStyleLocator; + + /** + * @var ?string + */ + protected $title; + + /** + * @var MenuItemInterface[] + */ + protected $items = []; + + /** + * @var int|null + */ + protected $selectedItem; + + /** + * @var bool + */ + protected $open = false; + + /** + * @var CliMenu|null + */ + protected $parent; + + /** + * @var array + */ + protected $defaultControlMappings = [ + '^P' => InputCharacter::UP, + 'k' => InputCharacter::UP, + '^K' => InputCharacter::DOWN, + 'j' => InputCharacter::DOWN, + "\r" => InputCharacter::ENTER, + ' ' => InputCharacter::ENTER, + 'l' => InputCharacter::LEFT, + 'm' => InputCharacter::RIGHT, + ]; + + /** + * @var array + */ + protected $customControlMappings = []; + + /** + * @var Frame + */ + private $currentFrame; + + public function __construct( + ?string $title, + array $items, + Terminal $terminal = null, + MenuStyle $style = null + ) { + $this->title = $title; + $this->items = $items; + $this->terminal = $terminal ?: TerminalFactory::fromSystem(); + $this->style = $style ?: new MenuStyle($this->terminal); + + $this->itemStyleLocator = new Locator(); + + $this->selectFirstItem(); + } + + /** + * Configure the terminal to work with CliMenu + */ + protected function configureTerminal() : void + { + $this->assertTerminalIsValidTTY(); + + $this->terminal->disableCanonicalMode(); + $this->terminal->disableEchoBack(); + $this->terminal->disableCursor(); + $this->terminal->clear(); + } + + /** + * Revert changes made to the terminal + */ + protected function tearDownTerminal() : void + { + $this->terminal->restoreOriginalConfiguration(); + $this->terminal->enableCanonicalMode(); + $this->terminal->enableEchoBack(); + $this->terminal->enableCursor(); + } + + private function assertTerminalIsValidTTY() : void + { + if (!$this->terminal->isInteractive()) { + throw new InvalidTerminalException('Terminal is not interactive (TTY)'); + } + } + + public function setTitle(string $title) : void + { + $this->title = $title; + } + + public function getTitle() : ?string + { + return $this->title; + } + + public function setParent(CliMenu $parent) : void + { + $this->parent = $parent; + } + + public function getParent() : ?CliMenu + { + return $this->parent; + } + + public function getTerminal() : Terminal + { + return $this->terminal; + } + + public function isOpen() : bool + { + return $this->open; + } + + /** + * Add a new Item to the menu + */ + public function addItem(MenuItemInterface $item) : void + { + $this->items[] = $item; + + $this->selectFirstItem(); + } + + /** + * Add multiple Items to the menu + */ + public function addItems(array $items) : void + { + foreach ($items as $item) { + $this->items[] = $item; + } + + $this->selectFirstItem(); + } + + /** + * Set Items of the menu + */ + public function setItems(array $items) : void + { + $this->selectedItem = null; + $this->items = $items; + + $this->selectFirstItem(); + } + + /** + * Set the selected pointer to the first selectable item + */ + private function selectFirstItem() : void + { + if (null === $this->selectedItem) { + foreach ($this->items as $key => $item) { + if ($item->canSelect()) { + $this->selectedItem = $key; + break; + } + } + } + } + + /** + * Disables the built-in VIM control mappings + */ + public function disableDefaultControlMappings() : void + { + $this->defaultControlMappings = []; + } + + /** + * Set default control mappings + */ + public function setDefaultControlMappings(array $defaultControlMappings) : void + { + $this->defaultControlMappings = $defaultControlMappings; + } + + /** + * Adds a custom control mapping + */ + public function addCustomControlMapping(string $input, callable $callable) : void + { + if (isset($this->defaultControlMappings[$input]) || isset($this->customControlMappings[$input])) { + throw new \InvalidArgumentException('Cannot rebind this input'); + } + + $this->customControlMappings[$input] = $callable; + } + + public function getCustomControlMappings() : array + { + return $this->customControlMappings; + } + + /** + * Shorthand function to add multiple custom control mapping at once + */ + public function addCustomControlMappings(array $map) : void + { + foreach ($map as $input => $callable) { + $this->addCustomControlMapping($input, $callable); + } + } + + /** + * Removes a custom control mapping + */ + public function removeCustomControlMapping(string $input) : void + { + if (!isset($this->customControlMappings[$input])) { + throw new \InvalidArgumentException('This input is not registered'); + } + + unset($this->customControlMappings[$input]); + } + + /** + * Display menu and capture input + */ + private function display() : void + { + $this->draw(); + + $reader = new NonCanonicalReader($this->terminal); + $reader->addControlMappings($this->defaultControlMappings); + + while ($this->isOpen()) { + $char = $reader->readCharacter(); + if (!$char->isHandledControl()) { + $rawChar = $char->get(); + if (isset($this->customControlMappings[$rawChar])) { + $this->customControlMappings[$rawChar]($this); + } + continue; + } + + switch ($char->getControl()) { + case InputCharacter::UP: + case InputCharacter::DOWN: + $this->moveSelectionVertically($char->getControl()); + $this->draw(); + break; + case InputCharacter::LEFT: + case InputCharacter::RIGHT: + $this->moveSelectionHorizontally($char->getControl()); + $this->draw(); + break; + case InputCharacter::ENTER: + $this->executeCurrentItem(); + break; + } + } + } + + /** + * Move the selection in a given direction, up / down + */ + protected function moveSelectionVertically(string $direction) : void + { + $itemKeys = array_keys($this->items); + + $increments = 0; + + do { + $increments++; + + if ($increments > count($itemKeys)) { + //full cycle detected, there must be no selected items + //in the menu, so stop trying to select one. + return; + } + + $direction === 'UP' + ? $this->selectedItem-- + : $this->selectedItem++; + + if ($this->selectedItem !== null && !array_key_exists($this->selectedItem, $this->items)) { + $this->selectedItem = $direction === 'UP' + ? (int) end($itemKeys) + : (int) reset($itemKeys); + } + } while (!$this->canSelect()); + } + + /** + * Move the selection in a given direction, left / right + */ + protected function moveSelectionHorizontally(string $direction) : void + { + if (!$this->items[$this->selectedItem] instanceof SplitItem) { + return; + } + + /** @var SplitItem $item */ + $item = $this->items[$this->selectedItem]; + $itemKeys = array_keys($item->getItems()); + $selectedItemIndex = $item->getSelectedItemIndex(); + + if (null === $selectedItemIndex) { + $selectedItemIndex = 0; + } + + do { + $direction === 'LEFT' + ? $selectedItemIndex-- + : $selectedItemIndex++; + + if (!array_key_exists($selectedItemIndex, $item->getItems())) { + $selectedItemIndex = $direction === 'LEFT' + ? (int) end($itemKeys) + : (int) reset($itemKeys); + } + } while (!$item->canSelectIndex($selectedItemIndex)); + + $item->setSelectedItemIndex($selectedItemIndex); + } + + /** + * Can the currently selected item actually be selected? + * + * For example: + * selectable item -> yes + * static item -> no + * split item with only static items -> no + * split item with at least one selectable item -> yes + * + * @return bool + */ + private function canSelect() : bool + { + return $this->items[$this->selectedItem]->canSelect(); + } + + /** + * Retrieve the item the user actually selected + * + */ + public function getSelectedItem() : MenuItemInterface + { + if (null === $this->selectedItem) { + throw new \RuntimeException('No selected item'); + } + + $item = $this->items[$this->selectedItem]; + return $item instanceof SplitItem + ? $item->getSelectedItem() + : $item; + } + + public function setSelectedItem(MenuItemInterface $item) : void + { + $key = array_search($item, $this->items, true); + + if (false === $key) { + throw new \InvalidArgumentException('Item does not exist in menu'); + } + + $this->selectedItem = (int) $key; + } + + public function getSelectedItemIndex() : int + { + if (null === $this->selectedItem) { + throw new \RuntimeException('No selected item'); + } + + return $this->selectedItem; + } + + public function getItemByIndex(int $index) : MenuItemInterface + { + if (!isset($this->items[$index])) { + throw new \RuntimeException('Item with index does not exist'); + } + + return $this->items[$index]; + } + + public function executeAsSelected(MenuItemInterface $item) : void + { + $current = $this->items[$this->selectedItem]; + $this->setSelectedItem($item); + $this->executeCurrentItem(); + $this->setSelectedItem($current); + } + + /** + * Execute the current item + */ + protected function executeCurrentItem() : void + { + $item = $this->getSelectedItem(); + + if ($item->canSelect()) { + $callable = $item->getSelectAction(); + if ($callable) { + $callable($this); + } + } + } + + /** + * If true we clear the whole terminal screen, useful + * for example when reducing the width of the menu, to not + * leave leftovers of the previous wider menu. + * + * Redraw the menu + */ + public function redraw(bool $clear = false) : void + { + if ($clear) { + $this->terminal->clear(); + } + + $this->assertOpen(); + $this->draw(); + } + + private function assertOpen() : void + { + if (!$this->isOpen()) { + throw new MenuNotOpenException; + } + } + + /** + * Draw the menu to STDOUT + */ + protected function draw() : void + { + $frame = new Frame; + + $frame->newLine(2); + + if ($this->style->getBorderTopWidth() > 0) { + $frame->addRows($this->style->getBorderTopRows()); + } + + if ($this->style->getPaddingTopBottom() > 0) { + $frame->addRows($this->style->getPaddingTopBottomRows()); + } + + if ($this->title) { + $frame->addRows($this->drawMenuItem(new StaticItem($this->title))); + $frame->addRows($this->drawMenuItem(new LineBreakItem($this->style->getTitleSeparator()))); + } + + array_map(function ($item, $index) use ($frame) { + $frame->addRows($this->drawMenuItem($item, $index === $this->selectedItem)); + }, $this->items, array_keys($this->items)); + + + if ($this->style->getPaddingTopBottom() > 0) { + $frame->addRows($this->style->getPaddingTopBottomRows()); + } + + if ($this->style->getBorderBottomWidth() > 0) { + $frame->addRows($this->style->getBorderBottomRows()); + } + + $frame->newLine(2); + + $this->terminal->moveCursorToTop(); + foreach ($frame->getRows() as $row) { + if ($row == "\n") { + $this->terminal->clearLine(); + } + $this->terminal->write($row); + } + $this->terminal->clearDown(); + + $this->currentFrame = $frame; + } + + /** + * Draw a menu item + */ + protected function drawMenuItem(MenuItemInterface $item, bool $selected = false) : array + { + $rows = $item->getRows($this->style, $selected); + + if ($item instanceof SplitItem) { + $selected = false; + } + + $invertedColoursSetCode = $selected + ? $this->style->getInvertedColoursSetCode() + : ''; + $invertedColoursUnsetCode = $selected + ? $this->style->getInvertedColoursUnsetCode() + : ''; + + if ($this->style->getBorderLeftWidth() || $this->style->getBorderRightWidth()) { + $borderColour = $this->style->getBorderColourCode(); + } else { + $borderColour = ''; + } + + return array_map(function ($row) use ($invertedColoursSetCode, $invertedColoursUnsetCode, $borderColour) { + return sprintf( + "%s%s%s%s%s%s%s%s%s%s%s%s\n", + str_repeat(' ', $this->style->getMargin()), + $borderColour, + str_repeat(' ', $this->style->getBorderLeftWidth()), + $this->style->getColoursSetCode(), + $invertedColoursSetCode, + str_repeat(' ', $this->style->getPaddingLeftRight()), + $row, + str_repeat(' ', $this->style->getRightHandPadding(mb_strlen(s::stripAnsiEscapeSequence($row)))), + $invertedColoursUnsetCode, + $borderColour, + str_repeat(' ', $this->style->getBorderRightWidth()), + $this->style->getColoursResetCode() + ); + }, $rows); + } + + /** + * @throws InvalidTerminalException + */ + public function open() : void + { + if ($this->isOpen()) { + return; + } + + if (count($this->items) === 0) { + throw new \RuntimeException('Menu must have at least 1 item before it can be opened'); + } + + $this->configureTerminal(); + $this->open = true; + $this->display(); + } + + /** + * Close the menu + * + * @throws InvalidTerminalException + */ + public function close() : void + { + $menu = $this; + + do { + $menu->closeThis(); + $menu = $menu->getParent(); + } while (null !== $menu); + + $this->tearDownTerminal(); + } + + public function closeThis() : void + { + $this->terminal->clean(); + $this->terminal->moveCursorToTop(); + $this->open = false; + } + + /** + * @return MenuItemInterface[] + */ + public function getItems() : array + { + return $this->items; + } + + public function removeItem(MenuItemInterface $item) : void + { + $key = array_search($item, $this->items, true); + + if (false === $key) { + throw new \InvalidArgumentException('Item does not exist in menu'); + } + + unset($this->items[$key]); + $this->items = array_values($this->items); + + if ($this->selectedItem === $key) { + $this->selectedItem = null; + $this->selectFirstItem(); + } + } + + public function getStyle() : MenuStyle + { + return $this->style; + } + + public function setStyle(MenuStyle $style) : void + { + $this->style = $style; + } + + public function setItemStyle(ItemStyle $style, string $styleClass) : void + { + $this->itemStyleLocator->setStyle($style, $styleClass); + } + + public function getItemStyle(string $styleClass) : ItemStyle + { + return $this->itemStyleLocator->getStyle($styleClass); + } + + public function getItemStyleForItem(MenuItemInterface $item) : ItemStyle + { + return $this->itemStyleLocator->getStyleForMenuItem($item); + } + + public function getStyleLocator() : Locator + { + return $this->itemStyleLocator; + } + + public function importStyles(CliMenu $menu) : void + { + if (!$this->style->hasChangedFromDefaults()) { + $this->style = $menu->style; + } + + $this->itemStyleLocator->importFrom($menu->itemStyleLocator); + } + + public function getCurrentFrame() : Frame + { + return $this->currentFrame; + } + + public function flash(string $text, MenuStyle $style = null) : Flash + { + $this->guardSingleLine($text); + + $style = $style ?? (new MenuStyle($this->terminal)) + ->setBg('yellow') + ->setFg('red'); + + return new Flash($this, $style, $this->terminal, $text); + } + + public function confirm(string $text, MenuStyle $style = null) : Confirm + { + $this->guardSingleLine($text); + + $style = $style ?? (new MenuStyle($this->terminal)) + ->setBg('yellow') + ->setFg('red'); + + return new Confirm($this, $style, $this->terminal, $text); + } + + public function cancellableConfirm(string $text, MenuStyle $style = null) : CancellableConfirm + { + $this->guardSingleLine($text); + + $style = $style ?? (new MenuStyle($this->terminal)) + ->setBg('yellow') + ->setFg('red'); + + return new CancellableConfirm($this, $style, $this->terminal, $text); + } + + public function askNumber(MenuStyle $style = null) : Number + { + $this->assertOpen(); + + $style = $style ?? (new MenuStyle($this->terminal)) + ->setBg('yellow') + ->setFg('red'); + + return new Number(new InputIO($this, $this->terminal), $style); + } + + public function askText(MenuStyle $style = null) : Text + { + $this->assertOpen(); + + $style = $style ?? (new MenuStyle($this->terminal)) + ->setBg('yellow') + ->setFg('red'); + + return new Text(new InputIO($this, $this->terminal), $style); + } + + public function askPassword(MenuStyle $style = null) : Password + { + $this->assertOpen(); + + $style = $style ?? (new MenuStyle($this->terminal)) + ->setBg('yellow') + ->setFg('red'); + + return new Password(new InputIO($this, $this->terminal), $style); + } + + private function guardSingleLine(string $text) : void + { + if (strpos($text, "\n") !== false) { + throw new \InvalidArgumentException; + } + } + + public function propagateStyles() : void + { + collect($this->items) + ->filter(function (int $k, MenuItemInterface $item) { + return $this->itemStyleLocator->hasStyleForMenuItem($item); + }) + ->filter(function (int $k, MenuItemInterface $item) { + return !$item->getStyle()->hasChangedFromDefaults(); + }) + ->each(function (int $k, $item) { + $item->setStyle(clone $this->getItemStyleForItem($item)); + }); + + + collect($this->items) + ->filter(function (int $k, MenuItemInterface $item) { + return $item instanceof PropagatesStyles; + }) + ->each(function (int $k, $item) { + $item->propagateStyles($this); + }); + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/CancellableConfirm.php b/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/CancellableConfirm.php new file mode 100644 index 0000000..3bf6b2d --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/CancellableConfirm.php @@ -0,0 +1,112 @@ + + */ +class CancellableConfirm extends Dialogue +{ + /** + * @var bool + */ + private $confirm = true; + + /** + * Display confirmation with a button with the given text + */ + public function display(string $confirmText = 'OK', string $cancelText = 'Cancel') : bool + { + $this->drawDialog($confirmText, $cancelText); + + $reader = new NonCanonicalReader($this->terminal); + + while ($char = $reader->readCharacter()) { + if ($char->isControl() && $char->getControl() === InputCharacter::ENTER) { + $this->parentMenu->redraw(); + return $this->confirm; + } elseif ($char->isControl() && $char->getControl() === InputCharacter::TAB || + ($char->isControl() && $char->getControl() === InputCharacter::RIGHT && $this->confirm) || + ($char->isControl() && $char->getControl() === InputCharacter::LEFT && !$this->confirm) + ) { + $this->confirm = !$this->confirm; + $this->drawDialog($confirmText, $cancelText); + } + } + } + + private function drawDialog(string $confirmText = 'OK', string $cancelText = 'Cancel'): void + { + $this->assertMenuOpen(); + + $this->terminal->moveCursorToRow($this->y); + + $promptWidth = mb_strlen($this->text) + 4; + + $buttonLength = mb_strlen($confirmText) + 6; + $buttonLength += mb_strlen($cancelText) + 7; + + $confirmButton = sprintf( + '%s%s < %s > %s%s', + $this->style->getOptionCode($this->confirm ? 'bold' : 'dim'), + $this->style->getInvertedColoursSetCode(), + $confirmText, + $this->style->getInvertedColoursUnsetCode(), + $this->style->getOptionCode($this->confirm ? 'bold' : 'dim', false) + ); + + $cancelButton = sprintf( + '%s%s < %s > %s%s', + $this->style->getOptionCode($this->confirm ? 'dim' : 'bold'), + $this->style->getInvertedColoursSetCode(), + $cancelText, + $this->style->getInvertedColoursUnsetCode(), + $this->style->getOptionCode($this->confirm ? 'dim' : 'bold', false) + ); + + $buttonRow = $confirmButton . " " . $cancelButton; + + if ($promptWidth < $buttonLength) { + $pad = ($buttonLength - $promptWidth) / 2; + $this->text = sprintf( + '%s%s%s', + str_repeat(' ', intval(round($pad, 0, 2) + $this->style->getPaddingLeftRight())), + $this->text, + str_repeat(' ', intval(round($pad, 0, 1) + $this->style->getPaddingLeftRight())) + ); + $promptWidth = mb_strlen($this->text) + 4; + } + + $leftFill = (int) (($promptWidth / 2) - ($buttonLength / 2)); + + $this->emptyRow(); + + $this->write(sprintf( + "%s%s%s%s%s\n", + $this->style->getColoursSetCode(), + str_repeat(' ', $this->style->getPaddingLeftRight()), + $this->text, + str_repeat(' ', $this->style->getPaddingLeftRight()), + $this->style->getColoursResetCode() + )); + + $this->emptyRow(); + + $this->write(sprintf( + "%s%s%s%s%s\n", + $this->style->getColoursSetCode(), + str_repeat(' ', $leftFill), + $buttonRow, + str_repeat(' ', (int) ceil($promptWidth - $leftFill - $buttonLength)), + $this->style->getColoursResetCode() + )); + + $this->emptyRow(); + + $this->terminal->moveCursorToTop(); + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Confirm.php b/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Confirm.php new file mode 100644 index 0000000..bdf9161 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Confirm.php @@ -0,0 +1,73 @@ + + */ +class Confirm extends Dialogue +{ + + /** + * Display confirmation with a button with the given text + */ + public function display(string $confirmText = 'OK') : void + { + $this->assertMenuOpen(); + + $this->terminal->moveCursorToRow($this->y); + + $promptWidth = mb_strlen($this->text) + 4; + + $this->emptyRow(); + + $this->write(sprintf( + "%s%s%s%s%s\n", + $this->style->getColoursSetCode(), + str_repeat(' ', $this->style->getPaddingLeftRight()), + $this->text, + str_repeat(' ', $this->style->getPaddingLeftRight()), + $this->style->getColoursResetCode() + )); + + $this->emptyRow(); + + $confirmText = sprintf(' < %s > ', $confirmText); + $leftFill = (int) (($promptWidth / 2) - (mb_strlen($confirmText) / 2)); + + $this->write(sprintf( + "%s%s%s%s%s%s%s\n", + $this->style->getColoursSetCode(), + str_repeat(' ', $leftFill), + $this->style->getInvertedColoursSetCode(), + $confirmText, + $this->style->getInvertedColoursUnsetCode(), + str_repeat(' ', (int) ceil($promptWidth - $leftFill - mb_strlen($confirmText))), + $this->style->getColoursResetCode() + )); + + $this->write(sprintf( + "%s%s%s%s%s\n", + $this->style->getColoursSetCode(), + str_repeat(' ', $this->style->getPaddingLeftRight()), + str_repeat(' ', mb_strlen($this->text)), + str_repeat(' ', $this->style->getPaddingLeftRight()), + $this->style->getColoursResetCode() + )); + + $this->terminal->moveCursorToTop(); + + $reader = new NonCanonicalReader($this->terminal); + + while ($char = $reader->readCharacter()) { + if ($char->isControl() && $char->getControl() === InputCharacter::ENTER) { + $this->parentMenu->redraw(); + return; + } + } + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Dialogue.php b/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Dialogue.php new file mode 100644 index 0000000..a55a029 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Dialogue.php @@ -0,0 +1,121 @@ + + */ +abstract class Dialogue +{ + /** + * @var MenuStyle + */ + protected $style; + + /** + * @var CliMenu + */ + protected $parentMenu; + + /** + * @var Terminal + */ + protected $terminal; + + /** + * @var string $text + */ + protected $text; + + /** + * @var bool $cancellable + */ + protected $cancellable; + + /** + * @var int + */ + protected $x; + + /** + * @var int + */ + protected $y; + + public function __construct( + CliMenu $parentMenu, + MenuStyle $menuStyle, + Terminal $terminal, + string $text + ) { + $this->style = $menuStyle; + $this->terminal = $terminal; + $this->text = $text; + $this->parentMenu = $parentMenu; + + $this->calculateCoordinates(); + } + + /** + * @throws MenuNotOpenException + */ + protected function assertMenuOpen() : void + { + if (!$this->parentMenu->isOpen()) { + throw new MenuNotOpenException; + } + } + + /** + * Calculate the co-ordinates to write the messages + */ + protected function calculateCoordinates() : void + { + //y + $textLines = count(explode("\n", $this->text)) + 2; + $this->y = (int) (ceil($this->parentMenu->getCurrentFrame()->count() / 2) - ceil($textLines / 2) + 1); + + //x + $parentStyle = $this->parentMenu->getStyle(); + $dialogueHalfLength = (int) ((mb_strlen($this->text) + ($this->style->getPaddingLeftRight() * 2)) / 2); + $widthHalfLength = (int) ceil($parentStyle->getWidth() / 2 + $parentStyle->getMargin()); + $this->x = $widthHalfLength - $dialogueHalfLength; + } + + /** + * Write an empty row + */ + protected function emptyRow() : void + { + $this->write( + sprintf( + "%s%s%s%s%s\n", + $this->style->getColoursSetCode(), + str_repeat(' ', $this->style->getPaddingLeftRight()), + str_repeat(' ', mb_strlen($this->text)), + str_repeat(' ', $this->style->getPaddingLeftRight()), + $this->style->getColoursResetCode() + ) + ); + } + + /** + * Write some text at a particular column + */ + protected function write(string $text, int $column = null) : void + { + $this->terminal->moveCursorToColumn($column ?: $this->x); + $this->terminal->write($text); + } + + public function getStyle() : MenuStyle + { + return $this->style; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Flash.php b/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Flash.php new file mode 100644 index 0000000..739a894 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Flash.php @@ -0,0 +1,43 @@ + + */ +class Flash extends Dialogue +{ + /** + * Flash a message on top of the menu which + * disappears on any keystroke. + */ + public function display() : void + { + $this->assertMenuOpen(); + + $this->terminal->moveCursorToRow($this->y); + + $this->emptyRow(); + + $this->write(sprintf( + "%s%s%s%s%s\n", + $this->style->getColoursSetCode(), + str_repeat(' ', $this->style->getPaddingLeftRight()), + $this->text, + str_repeat(' ', $this->style->getPaddingLeftRight()), + $this->style->getColoursResetCode() + )); + + $this->emptyRow(); + + $this->terminal->moveCursorToTop(); + + $reader = new NonCanonicalReader($this->terminal); + $reader->readCharacter(); + + $this->parentMenu->redraw(); + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Exception/CannotShrinkMenuException.php b/src/ncc/ThirdParty/php-school/cli-menu/Exception/CannotShrinkMenuException.php new file mode 100644 index 0000000..15bd2c4 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Exception/CannotShrinkMenuException.php @@ -0,0 +1,21 @@ + + */ +class InvalidShortcutException extends \RuntimeException +{ + public static function fromShortcut(string $shortcut) : self + { + return new self(sprintf('Shortcut key must be only one character. Got: "%s"', $shortcut)); + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Exception/InvalidTerminalException.php b/src/ncc/ThirdParty/php-school/cli-menu/Exception/InvalidTerminalException.php new file mode 100644 index 0000000..170deb9 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Exception/InvalidTerminalException.php @@ -0,0 +1,12 @@ + + */ +class InvalidTerminalException extends \Exception +{ + +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Exception/MenuNotOpenException.php b/src/ncc/ThirdParty/php-school/cli-menu/Exception/MenuNotOpenException.php new file mode 100644 index 0000000..f988e04 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Exception/MenuNotOpenException.php @@ -0,0 +1,12 @@ + + */ +class MenuNotOpenException extends \RuntimeException +{ + +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Frame.php b/src/ncc/ThirdParty/php-school/cli-menu/Frame.php new file mode 100644 index 0000000..7cb6d29 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Frame.php @@ -0,0 +1,47 @@ + + */ +class Frame implements \Countable +{ + /** + * @var array + */ + private $rows = []; + + public function newLine(int $count = 1) : void + { + foreach (range(1, $count) as $i) { + $this->rows[] = "\n"; + } + } + + public function addRows(array $rows = []) : void + { + foreach ($rows as $row) { + $this->rows[] = $row; + } + } + + public function addRow(string $row) : void + { + $this->rows[] = $row; + } + + public function count() : int + { + return count($this->rows); + } + + public function getRows() : array + { + return $this->rows; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Input/Input.php b/src/ncc/ThirdParty/php-school/cli-menu/Input/Input.php new file mode 100644 index 0000000..22e94f5 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Input/Input.php @@ -0,0 +1,32 @@ + + */ +interface Input +{ + public function ask() : InputResult; + + public function validate(string $input) : bool; + + public function setPromptText(string $promptText) : Input; + + public function getPromptText() : string; + + public function setValidationFailedText(string $validationFailedText) : Input; + + public function getValidationFailedText() : string; + + public function setPlaceholderText(string $placeholderText) : Input; + + public function getPlaceholderText() : string; + + public function filter(string $value) : string; + + public function getStyle() : MenuStyle; +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Input/InputIO.php b/src/ncc/ThirdParty/php-school/cli-menu/Input/InputIO.php new file mode 100644 index 0000000..14f81d5 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Input/InputIO.php @@ -0,0 +1,256 @@ + + */ +class InputIO +{ + /** + * @var CliMenu + */ + private $parentMenu; + + /** + * @var Terminal + */ + private $terminal; + + /** + * @var callable[][] + */ + private $callbacks = []; + + public function __construct(CliMenu $parentMenu, Terminal $terminal) + { + $this->terminal = $terminal; + $this->parentMenu = $parentMenu; + } + + public function collect(Input $input) : InputResult + { + $this->drawInput($input, $input->getPlaceholderText()); + + $inputValue = $input->getPlaceholderText(); + $havePlaceHolderValue = !empty($inputValue); + + $originalValue = $inputValue; + + $reader = new NonCanonicalReader($this->terminal); + + while ($char = $reader->readCharacter()) { + if ($char->isNotControl()) { + if ($havePlaceHolderValue) { + $inputValue = $char->get(); + $havePlaceHolderValue = false; + } else { + $inputValue .= $char->get(); + } + + $this->parentMenu->redraw(); + $this->drawInput($input, $inputValue); + continue; + } + + if ($char->isHandledControl()) { + switch ($char->getControl()) { + case InputCharacter::ESC: + $this->parentMenu->redraw(); + return new InputResult($originalValue); + case InputCharacter::ENTER: + if ($input->validate($inputValue)) { + $this->parentMenu->redraw(); + return new InputResult($inputValue); + } else { + $this->drawInputWithError($input, $inputValue); + continue 2; + } + + case InputCharacter::BACKSPACE: + $inputValue = substr($inputValue, 0, -1); + $this->parentMenu->redraw(); + $this->drawInput($input, $inputValue); + continue 2; + } + + if (!empty($this->callbacks[$char->getControl()])) { + foreach ($this->callbacks[$char->getControl()] as $callback) { + $inputValue = $callback($inputValue); + $this->drawInput($input, $inputValue); + } + } + } + } + } + + public function registerControlCallback(string $control, callable $callback) : void + { + if (!isset($this->callbacks[$control])) { + $this->callbacks[$control] = []; + } + + $this->callbacks[$control][] = $callback; + } + + private function getInputWidth(array $lines) : int + { + return max( + array_map( + function (string $line) { + return mb_strlen($line); + }, + $lines + ) + ) ? : 0; + } + + private function calculateYPosition() : int + { + $lines = 5; //1. empty 2. prompt text 3. empty 4. input 5. empty + + return (int) (ceil($this->parentMenu->getCurrentFrame()->count() / 2) - ceil($lines /2) + 1); + } + + private function calculateYPositionWithError() : int + { + $lines = 7; //1. empty 2. prompt text 3. empty 4. input 5. empty 6. error 7. empty + + return (int) (ceil($this->parentMenu->getCurrentFrame()->count() / 2) - ceil($lines /2) + 1); + } + + private function calculateXPosition(Input $input, string $userInput) : int + { + $width = $this->getInputWidth( + [ + $input->getPromptText(), + $input->getValidationFailedText(), + $userInput + ] + ); + + $parentStyle = $this->parentMenu->getStyle(); + $halfWidth = ($width + ($input->getStyle()->getPaddingLeftRight() * 2)) / 2; + $parentHalfWidth = ceil($parentStyle->getWidth() / 2 + $parentStyle->getMargin()); + + return (int) ($parentHalfWidth - $halfWidth); + } + + private function drawLine(Input $input, string $userInput, string $text) : void + { + $this->terminal->moveCursorToColumn($this->calculateXPosition($input, $userInput)); + + $line = sprintf( + "%s%s%s%s%s\n", + $input->getStyle()->getColoursSetCode(), + str_repeat(' ', $input->getStyle()->getPaddingLeftRight()), + $text, + str_repeat(' ', $input->getStyle()->getPaddingLeftRight()), + $input->getStyle()->getColoursResetCode() + ); + + $this->terminal->write($line); + } + + private function drawCenteredLine(Input $input, string $userInput, string $text) : void + { + $width = $this->getInputWidth( + [ + $input->getPromptText(), + $input->getValidationFailedText(), + $userInput + ] + ); + + $textLength = mb_strlen(StringUtil::stripAnsiEscapeSequence($text)); + $leftFill = (int) (($width / 2) - ($textLength / 2)); + $rightFill = (int) ceil($width - $leftFill - $textLength); + + $this->drawLine( + $input, + $userInput, + sprintf( + '%s%s%s', + str_repeat(' ', $leftFill), + $text, + str_repeat(' ', $rightFill) + ) + ); + } + + private function drawEmptyLine(Input $input, string $userInput) : void + { + $width = $this->getInputWidth( + [ + $input->getPromptText(), + $input->getValidationFailedText(), + $userInput + ] + ); + + $this->drawLine( + $input, + $userInput, + str_repeat(' ', $width) + ); + } + + private function drawInput(Input $input, string $userInput) : void + { + $this->terminal->moveCursorToRow($this->calculateYPosition()); + + $this->drawEmptyLine($input, $userInput); + $this->drawTitle($input, $userInput); + $this->drawEmptyLine($input, $userInput); + $this->drawInputField($input, $input->filter($userInput)); + $this->drawEmptyLine($input, $userInput); + } + + private function drawInputWithError(Input $input, string $userInput) : void + { + $this->terminal->moveCursorToRow($this->calculateYPositionWithError()); + + $this->drawEmptyLine($input, $userInput); + $this->drawTitle($input, $userInput); + $this->drawEmptyLine($input, $userInput); + $this->drawInputField($input, $input->filter($userInput)); + $this->drawEmptyLine($input, $userInput); + $this->drawCenteredLine( + $input, + $userInput, + $input->getValidationFailedText() + ); + $this->drawEmptyLine($input, $userInput); + } + + private function drawTitle(Input $input, string $userInput) : void + { + + $this->drawCenteredLine( + $input, + $userInput, + $input->getPromptText() + ); + } + + private function drawInputField(Input $input, string $userInput) : void + { + $this->drawCenteredLine( + $input, + $userInput, + sprintf( + '%s%s%s', + $input->getStyle()->getInvertedColoursSetCode(), + $userInput, + $input->getStyle()->getInvertedColoursUnsetCode() + ) + ); + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Input/InputResult.php b/src/ncc/ThirdParty/php-school/cli-menu/Input/InputResult.php new file mode 100644 index 0000000..28cb83a --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Input/InputResult.php @@ -0,0 +1,25 @@ + + */ +class InputResult +{ + /** + * @var string + */ + private $input; + + public function __construct(string $input) + { + $this->input = $input; + } + + public function fetch() : string + { + return $this->input; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Input/Number.php b/src/ncc/ThirdParty/php-school/cli-menu/Input/Number.php new file mode 100644 index 0000000..c7d741c --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Input/Number.php @@ -0,0 +1,130 @@ + + */ +class Number implements Input +{ + /** + * @var InputIO + */ + private $inputIO; + + /** + * @var string + */ + private $promptText = 'Enter a number:'; + + /** + * @var string + */ + private $validationFailedText = 'Not a valid number, try again'; + + /** + * @var string + */ + private $placeholderText = ''; + + /** + * @var null|callable + */ + private $validator; + + /** + * @var MenuStyle + */ + private $style; + + public function __construct(InputIO $inputIO, MenuStyle $style) + { + $this->inputIO = $inputIO; + $this->style = $style; + } + + public function setPromptText(string $promptText) : Input + { + $this->promptText = $promptText; + + return $this; + } + + public function getPromptText() : string + { + return $this->promptText; + } + + public function setValidationFailedText(string $validationFailedText) : Input + { + $this->validationFailedText = $validationFailedText; + + return $this; + } + + public function getValidationFailedText() : string + { + return $this->validationFailedText; + } + + public function setPlaceholderText(string $placeholderText) : Input + { + $this->placeholderText = $placeholderText; + + return $this; + } + + public function getPlaceholderText() : string + { + return $this->placeholderText; + } + + public function setValidator(callable $validator) : Input + { + $this->validator = $validator; + + return $this; + } + + public function ask() : InputResult + { + $this->inputIO->registerControlCallback(InputCharacter::UP, function (string $input) { + return $this->validate($input) ? (string) ((int) $input + 1) : $input; + }); + + $this->inputIO->registerControlCallback(InputCharacter::DOWN, function (string $input) { + return $this->validate($input) ? (string) ((int) $input - 1) : $input; + }); + + return $this->inputIO->collect($this); + } + + public function validate(string $input) : bool + { + if ($this->validator) { + $validator = $this->validator; + + if ($validator instanceof \Closure) { + $validator = $validator->bindTo($this); + } + + return $validator($input); + } + + return (bool) preg_match('/^-?\d+$/', $input); + } + + public function filter(string $value) : string + { + return $value; + } + + public function getStyle() : MenuStyle + { + return $this->style; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Input/Password.php b/src/ncc/ThirdParty/php-school/cli-menu/Input/Password.php new file mode 100644 index 0000000..0748c54 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Input/Password.php @@ -0,0 +1,131 @@ + + */ +class Password implements Input +{ + /** + * @var InputIO + */ + private $inputIO; + + /** + * @var string + */ + private $promptText = 'Enter password:'; + + /** + * @var string + */ + private $validationFailedText = 'Invalid password, try again'; + + /** + * @var string + */ + private $placeholderText = ''; + + /** + * @var null|callable + */ + private $validator; + + /** + * @var MenuStyle + */ + private $style; + + /** + * @var int + */ + private $passwordLength = 16; + + public function __construct(InputIO $inputIO, MenuStyle $style) + { + $this->inputIO = $inputIO; + $this->style = $style; + } + + public function setPromptText(string $promptText) : Input + { + $this->promptText = $promptText; + + return $this; + } + + public function getPromptText() : string + { + return $this->promptText; + } + + public function setValidationFailedText(string $validationFailedText) : Input + { + $this->validationFailedText = $validationFailedText; + + return $this; + } + + public function getValidationFailedText() : string + { + return $this->validationFailedText; + } + + public function setPlaceholderText(string $placeholderText) : Input + { + $this->placeholderText = $placeholderText; + + return $this; + } + + public function getPlaceholderText() : string + { + return $this->placeholderText; + } + + public function setValidator(callable $validator) : Input + { + $this->validator = $validator; + + return $this; + } + + public function ask() : InputResult + { + return $this->inputIO->collect($this); + } + + public function validate(string $input) : bool + { + if ($this->validator) { + $validator = $this->validator; + + if ($validator instanceof \Closure) { + $validator = $validator->bindTo($this); + } + + return $validator($input); + } + + return mb_strlen($input) >= $this->passwordLength; + } + + public function filter(string $value) : string + { + return str_repeat('*', mb_strlen($value)); + } + + public function getStyle() : MenuStyle + { + return $this->style; + } + + public function setPasswordLength(int $length) : int + { + return $this->passwordLength = $length; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Input/Text.php b/src/ncc/ThirdParty/php-school/cli-menu/Input/Text.php new file mode 100644 index 0000000..8435892 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Input/Text.php @@ -0,0 +1,121 @@ + + */ +class Text implements Input +{ + /** + * @var InputIO + */ + private $inputIO; + + /** + * @var string + */ + private $promptText = 'Enter text:'; + + /** + * @var string + */ + private $validationFailedText = 'Invalid, try again'; + + /** + * @var string + */ + private $placeholderText = ''; + + /** + * @var null|callable + */ + private $validator; + + /** + * @var MenuStyle + */ + private $style; + + public function __construct(InputIO $inputIO, MenuStyle $style) + { + $this->inputIO = $inputIO; + $this->style = $style; + } + + public function setPromptText(string $promptText) : Input + { + $this->promptText = $promptText; + + return $this; + } + + public function getPromptText() : string + { + return $this->promptText; + } + + public function setValidationFailedText(string $validationFailedText) : Input + { + $this->validationFailedText = $validationFailedText; + + return $this; + } + + public function getValidationFailedText() : string + { + return $this->validationFailedText; + } + + public function setPlaceholderText(string $placeholderText) : Input + { + $this->placeholderText = $placeholderText; + + return $this; + } + + public function getPlaceholderText() : string + { + return $this->placeholderText; + } + + public function setValidator(callable $validator) : Input + { + $this->validator = $validator; + + return $this; + } + + public function ask() : InputResult + { + return $this->inputIO->collect($this); + } + + public function validate(string $input) : bool + { + if ($this->validator) { + $validator = $this->validator; + + if ($validator instanceof \Closure) { + $validator = $validator->bindTo($this); + } + + return $validator($input); + } + + return !empty($input); + } + + public function filter(string $value) : string + { + return $value; + } + + public function getStyle() : MenuStyle + { + return $this->style; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/LICENSE b/src/ncc/ThirdParty/php-school/cli-menu/LICENSE new file mode 100644 index 0000000..cbada9b --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2015-2016 PHP School + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/AsciiArtItem.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/AsciiArtItem.php new file mode 100644 index 0000000..3a391cb --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/AsciiArtItem.php @@ -0,0 +1,187 @@ + + */ +class AsciiArtItem implements MenuItemInterface +{ + /** + * Possible positions of the ascii art + */ + const POSITION_CENTER = 'center'; + const POSITION_LEFT = 'left'; + const POSITION_RIGHT = 'right'; + + /** + * @var string + */ + private $text; + + /** + * @var string + */ + private $position; + + /** + * @var string + */ + private $alternateText; + + /** + * @var int + */ + private $artLength; + + /** + * @var DefaultStyle + */ + private $style; + + public function __construct(string $text, string $position = self::POSITION_CENTER, string $alt = '') + { + Assertion::inArray($position, [self::POSITION_CENTER, self::POSITION_RIGHT, self::POSITION_LEFT]); + + $this->setText($text); + $this->position = $position; + $this->alternateText = $alt; + + $this->style = new DefaultStyle(); + } + + /** + * The output text for the item + */ + public function getRows(MenuStyle $style, bool $selected = false) : array + { + if ($this->artLength > $style->getContentWidth()) { + $alternate = new StaticItem($this->alternateText); + return $alternate->getRows($style, false); + } + + $padding = $style->getContentWidth() - $this->artLength; + + return array_map(function ($row) use ($padding) { + switch ($this->position) { + case self::POSITION_LEFT: + break; + case self::POSITION_RIGHT: + $row = sprintf('%s%s', str_repeat(' ', $padding), $row); + break; + case self::POSITION_CENTER: + default: + $left = (int) ceil($padding / 2); + $row = sprintf('%s%s', str_repeat(' ', $left), $row); + break; + } + + return $row; + }, explode("\n", $this->text)); + } + + /** + * Can the item be selected + */ + public function canSelect() : bool + { + return false; + } + + /** + * Execute the items callable if required + */ + public function getSelectAction() : ?callable + { + return null; + } + + /** + * Return the raw string of text + */ + public function getText() : string + { + return $this->text; + } + + /** + * Set the raw string of text + */ + public function setText(string $text) : void + { + $this->text = implode("\n", array_map(function (string $line) { + return rtrim($line, ' '); + }, explode("\n", $text))); + + $this->calculateArtLength(); + } + + /** + * Calculate the length of the art + */ + private function calculateArtLength() : void + { + $this->artLength = (int) max(array_map('mb_strlen', explode("\n", $this->text))); + } + + /** + * Return the length of the art + */ + public function getArtLength() : int + { + return $this->artLength; + } + + public function getPosition() : string + { + return $this->position; + } + + public function getAlternateText() : string + { + return $this->alternateText; + } + + /** + * Whether or not the menu item is showing the menustyle extra value + */ + public function showsItemExtra() : bool + { + return false; + } + + /** + * Enable showing item extra + */ + public function showItemExtra() : void + { + //noop + } + + /** + * Disable showing item extra + */ + public function hideItemExtra() : void + { + //noop + } + + /** + * @return DefaultStyle + */ + public function getStyle() : ItemStyle + { + return $this->style; + } + + public function setStyle(DefaultStyle $style) : void + { + $this->style = $style; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/CheckboxItem.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/CheckboxItem.php new file mode 100644 index 0000000..6d0cead --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/CheckboxItem.php @@ -0,0 +1,172 @@ +text = $text; + $this->selectAction = $selectAction; + $this->showItemExtra = $showItemExtra; + $this->disabled = $disabled; + + $this->style = new CheckboxStyle(); + } + + /** + * The output text for the item + */ + public function getRows(MenuStyle $style, bool $selected = false) : array + { + return (new SelectableItemRenderer())->render($style, $this, $selected, $this->disabled); + } + + /** + * Return the raw string of text + */ + public function getText() : string + { + return $this->text; + } + + /** + * Set the raw string of text + */ + public function setText(string $text) : void + { + $this->text = $text; + } + + /** + * Execute the items callable if required + */ + public function getSelectAction() : ?callable + { + return function (CliMenu $cliMenu) { + $this->toggle(); + $cliMenu->redraw(); + + return ($this->selectAction)($cliMenu); + }; + } + + /** + * Can the item be selected + */ + public function canSelect() : bool + { + return !$this->disabled; + } + + /** + * Whether or not we are showing item extra + */ + public function showsItemExtra() : bool + { + return $this->showItemExtra; + } + + /** + * Enable showing item extra + */ + public function showItemExtra() : void + { + $this->showItemExtra = true; + } + + /** + * Disable showing item extra + */ + public function hideItemExtra() : void + { + $this->showItemExtra = false; + } + + /** + * Whether or not the item is checked + */ + public function getChecked() : bool + { + return $this->checked; + } + + /** + * Sets checked state to true + */ + public function setChecked() : void + { + $this->checked = true; + } + + /** + * Sets checked state to false + */ + public function setUnchecked() : void + { + $this->checked = false; + } + + /** + * Toggles checked state + */ + public function toggle() : void + { + $this->checked = !$this->checked; + } + + /** + * @return CheckboxStyle + */ + public function getStyle() : ItemStyle + { + return $this->style; + } + + public function setStyle(CheckboxStyle $style) : void + { + $this->style = $style; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/LineBreakItem.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/LineBreakItem.php new file mode 100644 index 0000000..e908355 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/LineBreakItem.php @@ -0,0 +1,126 @@ + + */ +class LineBreakItem implements MenuItemInterface +{ + /** + * @var string + */ + private $breakChar; + + /** + * @var int + */ + private $lines; + + /** + * @var DefaultStyle + */ + private $style; + + public function __construct(string $breakChar = ' ', int $lines = 1) + { + $this->breakChar = $breakChar; + $this->lines = $lines; + + $this->style = new DefaultStyle(); + } + + /** + * The output text for the item + */ + public function getRows(MenuStyle $style, bool $selected = false) : array + { + return explode( + "\n", + rtrim(str_repeat(sprintf( + "%s\n", + mb_substr(str_repeat($this->breakChar, $style->getContentWidth()), 0, $style->getContentWidth()) + ), $this->lines)) + ); + } + + /** + * Can the item be selected + */ + public function canSelect() : bool + { + return false; + } + + /** + * Execute the items callable if required + */ + public function getSelectAction() : ?callable + { + return null; + } + + /** + * Return the raw string of text + */ + public function getText() : string + { + return $this->breakChar; + } + + /** + * Set the raw string of text + */ + public function setText(string $text) : void + { + $this->breakChar = $text; + } + + /** + * Whether or not the menu item is showing the menustyle extra value + */ + public function showsItemExtra() : bool + { + return false; + } + + public function getLines() : int + { + return $this->lines; + } + + /** + * Enable showing item extra + */ + public function showItemExtra() : void + { + //noop + } + + /** + * Disable showing item extra + */ + public function hideItemExtra() : void + { + //noop + } + + /** + * @return DefaultStyle + */ + public function getStyle() : ItemStyle + { + return $this->style; + } + + public function setStyle(DefaultStyle $style) : void + { + $this->style = $style; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/MenuItemInterface.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/MenuItemInterface.php new file mode 100644 index 0000000..81e7d7c --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/MenuItemInterface.php @@ -0,0 +1,55 @@ + + */ +interface MenuItemInterface +{ + /** + * The output text for the item + */ + public function getRows(MenuStyle $style, bool $selected = false) : array; + + /** + * Return the raw string of text + */ + public function getText() : string; + + /** + * Can the item be selected + */ + public function canSelect() : bool; + + /** + * Execute the items callable if required + */ + public function getSelectAction() : ?callable; + + /** + * Whether or not the menu item is showing the menustyle extra value + */ + public function showsItemExtra() : bool; + + /** + * Enable showing item extra + */ + public function showItemExtra() : void; + + /** + * Disable showing item extra + */ + public function hideItemExtra() : void; + + /** + * Get the items style object. Can and + * should be subclassed to provide bespoke + * behaviour. + */ + public function getStyle() : ItemStyle; +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/MenuMenuItem.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/MenuMenuItem.php new file mode 100644 index 0000000..fee929a --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/MenuMenuItem.php @@ -0,0 +1,157 @@ + + */ +class MenuMenuItem implements MenuItemInterface, PropagatesStyles +{ + /** + * @var string + */ + private $text; + + /** + * @var CliMenu + */ + private $subMenu; + + /** + * @var bool + */ + private $showItemExtra = false; + + /** + * @var bool + */ + private $disabled; + + /** + * @var SelectableStyle + */ + private $style; + + public function __construct( + string $text, + CliMenu $subMenu, + bool $disabled = false + ) { + $this->text = $text; + $this->subMenu = $subMenu; + $this->disabled = $disabled; + + $this->style = new SelectableStyle(); + } + + /** + * The output text for the item + */ + public function getRows(MenuStyle $style, bool $selected = false) : array + { + return (new SelectableItemRenderer())->render($style, $this, $selected, $this->disabled); + } + + /** + * Return the raw string of text + */ + public function getText() : string + { + return $this->text; + } + + /** + * Set the raw string of text + */ + public function setText(string $text) : void + { + $this->text = $text; + } + + /** + * Execute the items callable if required + */ + public function getSelectAction() : ?callable + { + return function (CliMenu $menu) { + $this->showSubMenu($menu); + }; + } + + /** + * Returns the sub menu + */ + public function getSubMenu() : CliMenu + { + return $this->subMenu; + } + + /** + * Display the sub menu + */ + public function showSubMenu(CliMenu $parentMenu) : void + { + $parentMenu->closeThis(); + $this->subMenu->open(); + } + + /** + * Can the item be selected + */ + public function canSelect() : bool + { + return !$this->disabled; + } + + /** + * Enable showing item extra + */ + public function showItemExtra() : void + { + $this->showItemExtra = true; + } + + /** + * Whether or not we are showing item extra + */ + public function showsItemExtra() : bool + { + return $this->showItemExtra; + } + + /** + * Disable showing item extra + */ + public function hideItemExtra() : void + { + $this->showItemExtra = false; + } + + /** + * @return SelectableStyle + */ + public function getStyle() : ItemStyle + { + return $this->style; + } + + public function setStyle(SelectableStyle $style) : void + { + $this->style = $style; + } + + /** + * @inheritDoc + */ + public function propagateStyles(CliMenu $parent): void + { + $this->getSubMenu()->importStyles($parent); + $this->getSubMenu()->propagateStyles(); + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/PropagatesStyles.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/PropagatesStyles.php new file mode 100644 index 0000000..5c41206 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/PropagatesStyles.php @@ -0,0 +1,16 @@ +text = $text; + $this->selectAction = $selectAction; + $this->showItemExtra = $showItemExtra; + $this->disabled = $disabled; + + $this->style = new RadioStyle(); + } + + /** + * The output text for the item + */ + public function getRows(MenuStyle $style, bool $selected = false) : array + { + return (new SelectableItemRenderer())->render($style, $this, $selected, $this->disabled); + } + + /** + * Return the raw string of text + */ + public function getText() : string + { + return $this->text; + } + + /** + * Set the raw string of text + */ + public function setText(string $text) : void + { + $this->text = $text; + } + + /** + * Execute the items callable if required + */ + public function getSelectAction() : ?callable + { + return function (CliMenu $cliMenu) { + $parentItem = $cliMenu->getItemByIndex($cliMenu->getSelectedItemIndex()); + + $siblings = $parentItem instanceof SplitItem + ? $parentItem->getItems() + : $cliMenu->getItems(); + + $filtered = array_filter( + $siblings, + function (MenuItemInterface $item) { + return $item instanceof self; + } + ); + + array_walk( + $filtered, + function (RadioItem $item) { + $item->setUnchecked(); + } + ); + + $this->setChecked(); + $cliMenu->redraw(); + + return ($this->selectAction)($cliMenu); + }; + } + + /** + * Can the item be selected + */ + public function canSelect() : bool + { + return !$this->disabled; + } + + /** + * Whether or not we are showing item extra + */ + public function showsItemExtra() : bool + { + return $this->showItemExtra; + } + + /** + * Enable showing item extra + */ + public function showItemExtra() : void + { + $this->showItemExtra = true; + } + + /** + * Disable showing item extra + */ + public function hideItemExtra() : void + { + $this->showItemExtra = false; + } + + /** + * Whether or not the item is checked + */ + public function getChecked() : bool + { + return $this->checked; + } + + /** + * Sets checked state to true + */ + public function setChecked() : void + { + $this->checked = true; + } + + /** + * Sets checked state to false + */ + public function setUnchecked() : void + { + $this->checked = false; + } + + /** + * Toggles checked state + */ + public function toggle() : void + { + $this->checked = !$this->checked; + } + + /** + * @return RadioStyle + */ + public function getStyle() : ItemStyle + { + return $this->style; + } + + public function setStyle(RadioStyle $style) : void + { + $this->style = $style; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SelectableItem.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SelectableItem.php new file mode 100644 index 0000000..d5364e8 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SelectableItem.php @@ -0,0 +1,132 @@ + + */ +class SelectableItem implements MenuItemInterface +{ + /** + * @var string + */ + private $text; + + /** + * @var callable + */ + private $selectAction; + + /** + * @var bool + */ + private $showItemExtra; + + /** + * @var bool + */ + private $disabled; + + /** + * @var SelectableStyle + */ + private $style; + + public function __construct( + string $text, + callable $selectAction, + bool $showItemExtra = false, + bool $disabled = false + ) { + $this->text = $text; + $this->selectAction = $selectAction; + $this->showItemExtra = $showItemExtra; + $this->disabled = $disabled; + + $this->style = new SelectableStyle(); + } + + /** + * The output text for the item + */ + public function getRows(MenuStyle $style, bool $selected = false) : array + { + return (new SelectableItemRenderer())->render($style, $this, $selected, $this->disabled); + } + + /** + * Return the raw string of text + */ + public function getText() : string + { + return $this->text; + } + + /** + * Set the raw string of text + */ + public function setText(string $text) : void + { + $this->text = $text; + } + + /** + * Execute the items callable if required + */ + public function getSelectAction() : ?callable + { + return $this->selectAction; + } + + /** + * Can the item be selected + */ + public function canSelect() : bool + { + return !$this->disabled; + } + + /** + * Whether or not we are showing item extra + */ + public function showsItemExtra() : bool + { + return $this->showItemExtra; + } + + /** + * Enable showing item extra + */ + public function showItemExtra() : void + { + $this->showItemExtra = true; + } + + /** + * Disable showing item extra + */ + public function hideItemExtra() : void + { + $this->showItemExtra = false; + } + + /** + * @return SelectableStyle + */ + public function getStyle() : ItemStyle + { + return $this->style; + } + + public function setStyle(SelectableStyle $style) : void + { + $this->style = $style; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SelectableItemRenderer.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SelectableItemRenderer.php new file mode 100644 index 0000000..85aeee9 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SelectableItemRenderer.php @@ -0,0 +1,66 @@ +getStyle(); + $marker = $itemStyle->getMarker($item, $selected); + $availableTextWidth = $this->getAvailableTextWidth($menuStyle, $itemStyle); + + return mapWithKeys( + $this->wrapAndIndentText($marker, $item->getText(), $availableTextWidth), + function (int $key, string $row) use ($menuStyle, $item, $availableTextWidth, $disabled) { + $text = $disabled ? $menuStyle->getDisabledItemText($row) : $row; + + return $key === 0 && $item->showsItemExtra() + ? $this->lineWithExtra($text, $availableTextWidth, $item->getStyle()) + : $text; + } + ); + } + + public function wrapAndIndentText(string $marker, string $text, int $availableWidth) : array + { + return explode( + "\n", + s::wordwrap( + "{$marker}{$text}", + $availableWidth, + sprintf("\n%s", $this->emptyString(mb_strlen($marker))) + ) + ); + } + + public function lineWithExtra(string $text, int $availableWidth, ItemStyle $itemStyle) : string + { + return sprintf( + '%s%s %s', + $text, + $this->emptyString($availableWidth - s::length($text)), + $itemStyle->getItemExtra() + ); + } + + public function emptyString(int $numCharacters) : string + { + return str_repeat(' ', $numCharacters); + } + + public function getAvailableTextWidth(MenuStyle $menuStyle, ItemStyle $itemStyle) : int + { + return $itemStyle->getDisplaysExtra() + ? $menuStyle->getContentWidth() - (mb_strlen($itemStyle->getItemExtra()) + 2) + : $menuStyle->getContentWidth(); + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SplitItem.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SplitItem.php new file mode 100644 index 0000000..96b0359 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SplitItem.php @@ -0,0 +1,388 @@ + + */ +class SplitItem implements MenuItemInterface, PropagatesStyles +{ + /** + * @var array + */ + private $items = []; + + /** + * @var int|null + */ + private $selectedItemIndex; + + /** + * @var bool + */ + private $canBeSelected = true; + + /** + * @var int + */ + private $gutter = 2; + + /** + * @var DefaultStyle + */ + private $style; + + /** + * @var array + */ + private static $blacklistedItems = [ + \PhpSchool\CliMenu\MenuItem\AsciiArtItem::class, + \PhpSchool\CliMenu\MenuItem\LineBreakItem::class, + \PhpSchool\CliMenu\MenuItem\SplitItem::class, + ]; + + public function __construct(array $items = []) + { + $this->addItems($items); + $this->setDefaultSelectedItem(); + + $this->style = new DefaultStyle(); + } + + public function getGutter() : int + { + return $this->gutter; + } + + public function setGutter(int $gutter) : void + { + Assertion::greaterOrEqualThan($gutter, 0); + $this->gutter = $gutter; + } + + public function addItem(MenuItemInterface $item) : self + { + foreach (self::$blacklistedItems as $bl) { + if ($item instanceof $bl) { + throw new \InvalidArgumentException("Cannot add a $bl to a SplitItem"); + } + } + $this->items[] = $item; + $this->setDefaultSelectedItem(); + return $this; + } + + public function addItems(array $items) : self + { + foreach ($items as $item) { + $this->addItem($item); + } + + return $this; + } + + public function setItems(array $items) : self + { + $this->items = []; + $this->addItems($items); + return $this; + } + + /** + * Select default item + */ + private function setDefaultSelectedItem() : void + { + foreach ($this->items as $index => $item) { + if ($item->canSelect()) { + $this->canBeSelected = true; + $this->selectedItemIndex = $index; + return; + } + } + + $this->canBeSelected = false; + $this->selectedItemIndex = null; + } + + /** + * The output text for the item + */ + public function getRows(MenuStyle $style, bool $selected = false) : array + { + $numberOfItems = count($this->items); + + if ($numberOfItems === 0) { + throw new \RuntimeException(sprintf('There should be at least one item added to: %s', __CLASS__)); + } + + if (!$selected) { + $this->setDefaultSelectedItem(); + } + + $largestItemExtra = $this->calculateItemExtra(); + + $length = $largestItemExtra > 0 + ? floor($style->getContentWidth() / $numberOfItems) - ($largestItemExtra + 2) + : floor($style->getContentWidth() / $numberOfItems); + + $length -= $this->gutter; + $length = (int) $length; + + $missingLength = $style->getContentWidth() % $numberOfItems; + + return $this->buildRows( + mapWithKeys($this->items, function (int $index, MenuItemInterface $item) use ($selected, $length, $style) { + $isSelected = $selected && $index === $this->selectedItemIndex; + + $marker = $item->getStyle()->getMarker($item, $isSelected); + + $itemExtra = ''; + if ($item->getStyle()->getDisplaysExtra()) { + $itemExtraVal = $item->getStyle()->getItemExtra(); + $itemExtra = $item->showsItemExtra() + ? sprintf(' %s', $itemExtraVal) + : sprintf(' %s', str_repeat(' ', mb_strlen($itemExtraVal))); + } + + return $this->buildCell( + explode( + "\n", + StringUtil::wordwrap( + sprintf('%s%s', $marker, $item->getText()), + $length, + sprintf("\n%s", str_repeat(' ', mb_strlen($marker))) + ) + ), + $length, + $style, + $isSelected, + $itemExtra + ); + }), + $missingLength, + $length, + $largestItemExtra + ); + } + + private function buildRows(array $cells, int $missingLength, int $length, int $largestItemExtra) : array + { + $extraPadLength = $largestItemExtra > 0 ? 2 + $largestItemExtra : 0; + + return array_map( + function ($i) use ($cells, $length, $missingLength, $extraPadLength) { + return $this->buildRow($cells, $i, $length, $missingLength, $extraPadLength); + }, + range(0, max(array_map('count', $cells)) - 1) + ); + } + + private function buildRow(array $cells, int $index, int $length, int $missingLength, int $extraPadLength) : string + { + return sprintf( + '%s%s', + implode( + '', + array_map( + function ($cell) use ($index, $length, $extraPadLength) { + return $cell[$index] ?? str_repeat(' ', $length + $this->gutter + $extraPadLength); + }, + $cells + ) + ), + str_repeat(' ', $missingLength) + ); + } + + private function buildCell( + array $content, + int $length, + MenuStyle $style, + bool $isSelected, + string $itemExtra + ) : array { + return array_map(function ($row, $index) use ($length, $style, $isSelected, $itemExtra) { + $invertedColoursSetCode = $isSelected + ? $style->getInvertedColoursSetCode() + : ''; + $invertedColoursUnsetCode = $isSelected + ? $style->getInvertedColoursUnsetCode() + : ''; + + return sprintf( + '%s%s%s%s%s%s', + $invertedColoursSetCode, + $row, + str_repeat(' ', $length - mb_strlen($row)), + $index === 0 ? $itemExtra : str_repeat(' ', mb_strlen($itemExtra)), + $invertedColoursUnsetCode, + str_repeat(' ', $this->gutter) + ); + }, $content, array_keys($content)); + } + + /** + * Is there an item with this index and can it be + * selected? + */ + public function canSelectIndex(int $index) : bool + { + return isset($this->items[$index]) && $this->items[$index]->canSelect(); + } + + /** + * Set the item index which should be selected. If the item does + * not exist then throw an exception. + */ + public function setSelectedItemIndex(int $index) : void + { + if (!isset($this->items[$index])) { + throw new \InvalidArgumentException(sprintf('Index: "%s" does not exist', $index)); + } + + $this->selectedItemIndex = $index; + } + + /** + * Get the currently select item index. + * May be null in case of no selectable item. + */ + public function getSelectedItemIndex() : ?int + { + return $this->selectedItemIndex; + } + + /** + * Get the currently selected item - if no items are selectable + * then throw an exception. + */ + public function getSelectedItem() : MenuItemInterface + { + if (null === $this->selectedItemIndex) { + throw new \RuntimeException('No item is selected'); + } + + return $this->items[$this->selectedItemIndex]; + } + + public function getItems() : array + { + return $this->items; + } + + /** + * Can the item be selected + * In this case, it indicates if at least 1 item inside the SplitItem can be selected + */ + public function canSelect() : bool + { + return $this->canBeSelected; + } + + /** + * Execute the items callable if required + */ + public function getSelectAction() : ?callable + { + return null; + } + + /** + * Whether or not the menu item is showing the menustyle extra value + */ + public function showsItemExtra() : bool + { + return false; + } + + /** + * Enable showing item extra + */ + public function showItemExtra() : void + { + //noop + } + + /** + * Disable showing item extra + */ + public function hideItemExtra() : void + { + //noop + } + + /** + * Nothing to return with SplitItem + */ + public function getText() : string + { + throw new \BadMethodCallException(sprintf('Not supported on: %s', __CLASS__)); + } + + /** + * Finds largest itemExtra value in items + */ + private function calculateItemExtra() : int + { + return max(array_map( + function (MenuItemInterface $item) { + return mb_strlen($item->getStyle()->getItemExtra()); + }, + array_filter($this->items, function (MenuItemInterface $item) { + return $item->getStyle()->getDisplaysExtra(); + }) + )); + } + + /** + * @return DefaultStyle + */ + public function getStyle(): ItemStyle + { + return $this->style; + } + + public function setStyle(DefaultStyle $style): void + { + $this->style = $style; + } + + /** + * @inheritDoc + */ + public function propagateStyles(CliMenu $parent): void + { + collect($this->items) + ->filter(function (int $k, MenuItemInterface $item) use ($parent) { + return $parent->getStyleLocator()->hasStyleForMenuItem($item); + }) + ->filter(function (int $k, MenuItemInterface $item) { + return !$item->getStyle()->hasChangedFromDefaults(); + }) + ->each(function (int $k, $item) use ($parent) { + $item->setStyle(clone $parent->getItemStyleForItem($item)); + }); + + collect($this->items) + ->filter(function (int $k, MenuItemInterface $item) { + return $item instanceof PropagatesStyles; + }) + ->each(function (int $k, $item) use ($parent) { + $item->propagateStyles($parent); + }); + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/StaticItem.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/StaticItem.php new file mode 100644 index 0000000..798101e --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/StaticItem.php @@ -0,0 +1,109 @@ + + */ +class StaticItem implements MenuItemInterface +{ + /** + * @var string + */ + private $text; + + /** + * @var DefaultStyle + */ + private $style; + + public function __construct(string $text) + { + $this->text = $text; + + $this->style = new DefaultStyle(); + } + + /** + * The output text for the item + */ + public function getRows(MenuStyle $style, bool $selected = false) : array + { + return explode("\n", StringUtil::wordwrap($this->text, $style->getContentWidth())); + } + + /** + * Return the raw string of text + */ + public function getText() : string + { + return $this->text; + } + + /** + * Set the raw string of text + */ + public function setText(string $text) : void + { + $this->text = $text; + } + + /** + * Execute the items callable if required + */ + public function getSelectAction() : ?callable + { + return null; + } + + /** + * Can the item be selected + */ + public function canSelect() : bool + { + return false; + } + + /** + * Whether or not we are showing item extra + */ + public function showsItemExtra() : bool + { + return false; + } + + /** + * Enable showing item extra + */ + public function showItemExtra() : void + { + //noop + } + + /** + * Disable showing item extra + */ + public function hideItemExtra() : void + { + //noop + } + + /** + * @return DefaultStyle + */ + public function getStyle() : ItemStyle + { + return $this->style; + } + + public function setStyle(DefaultStyle $style) : void + { + $this->style = $style; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuStyle.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuStyle.php new file mode 100644 index 0000000..f06315b --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/MenuStyle.php @@ -0,0 +1,852 @@ + + */ +class MenuStyle +{ + /** + * @var Terminal + */ + protected $terminal; + + /** + * @var string + */ + protected $fg; + + /** + * @var string + */ + protected $bg; + + /** + * The width of the menu. Including borders and padding. + * Does not include margin. + * + * May not be the value that was requested in the + * circumstance that the terminal is smaller then the + * requested width. + * + * @var int + */ + protected $width; + + /** + * In case the requested width is wider than the terminal + * then we shrink the width to fit the terminal. We keep + * the requested size in case the margins are changed and + * we need to recalculate the width. + * + * @var int + */ + private $requestedWidth; + + /** + * @var int + */ + protected $margin = 0; + + /** + * @var int + */ + protected $paddingTopBottom = 0; + + /** + * @var int + */ + protected $paddingLeftRight = 0; + + /** + * @var array + */ + private $paddingTopBottomRows = []; + + /** + * @var int + */ + protected $contentWidth; + + /** + * @var string + */ + private $itemExtra; + + /** + * @var bool + */ + private $displaysExtra; + + /** + * @var string + */ + private $titleSeparator; + + /** + * @var string + */ + private $coloursSetCode; + + /** + * @var string + */ + private $invertedColoursSetCode = "\033[7m"; + + /** + * @var string + */ + private $invertedColoursUnsetCode = "\033[27m"; + + /** + * @var string + */ + private $coloursResetCode = "\033[0m"; + + /** + * @var int + */ + private $borderTopWidth = 0; + + /** + * @var int + */ + private $borderRightWidth = 0; + + /** + * @var int + */ + private $borderBottomWidth = 0; + + /** + * @var int + */ + private $borderLeftWidth = 0; + + /** + * @var string + */ + private $borderColour = 'white'; + + /** + * @var array + */ + private $borderTopRows = []; + + /** + * @var array + */ + private $borderBottomRows = []; + + /** + * @var bool + */ + private $marginAuto = false; + + /** + * @var bool + */ + private $debugMode = false; + + /** + * Default Values + * + * @var array + */ + private static $defaultStyleValues = [ + 'fg' => 'white', + 'bg' => 'blue', + 'width' => 100, + 'paddingTopBottom' => 1, + 'paddingLeftRight' => 2, + 'margin' => 2, + 'itemExtra' => '✔', + 'displaysExtra' => false, + 'titleSeparator' => '=', + 'borderTopWidth' => 0, + 'borderRightWidth' => 0, + 'borderBottomWidth' => 0, + 'borderLeftWidth' => 0, + 'borderColour' => 'white', + 'marginAuto' => false, + ]; + + /** + * @var array + */ + private static $availableForegroundColors = [ + 'black' => 30, + 'red' => 31, + 'green' => 32, + 'yellow' => 33, + 'blue' => 34, + 'magenta' => 35, + 'cyan' => 36, + 'white' => 37, + 'default' => 39, + ]; + + /** + * @var array + */ + private static $availableBackgroundColors = [ + 'black' => 40, + 'red' => 41, + 'green' => 42, + 'yellow' => 43, + 'blue' => 44, + 'magenta' => 45, + 'cyan' => 46, + 'white' => 47, + 'default' => 49, + ]; + + /** + * @var array + */ + private static $availableOptions = [ + 'bold' => ['set' => 1, 'unset' => 22], + 'dim' => ['set' => 2, 'unset' => 22], + 'underscore' => ['set' => 4, 'unset' => 24], + 'blink' => ['set' => 5, 'unset' => 25], + 'reverse' => ['set' => 7, 'unset' => 27], + 'conceal' => ['set' => 8, 'unset' => 28] + ]; + + /** + * Initialise style + */ + public function __construct(Terminal $terminal = null) + { + $this->terminal = $terminal ?: TerminalFactory::fromSystem(); + + $this->fg = self::$defaultStyleValues['fg']; + $this->bg = self::$defaultStyleValues['bg']; + + $this->generateColoursSetCode(); + + $this->setWidth(self::$defaultStyleValues['width']); + $this->setPaddingTopBottom(self::$defaultStyleValues['paddingTopBottom']); + $this->setPaddingLeftRight(self::$defaultStyleValues['paddingLeftRight']); + $this->setMargin(self::$defaultStyleValues['margin']); + $this->setItemExtra(self::$defaultStyleValues['itemExtra']); + $this->setDisplaysExtra(self::$defaultStyleValues['displaysExtra']); + $this->setTitleSeparator(self::$defaultStyleValues['titleSeparator']); + $this->setBorderTopWidth(self::$defaultStyleValues['borderTopWidth']); + $this->setBorderRightWidth(self::$defaultStyleValues['borderRightWidth']); + $this->setBorderBottomWidth(self::$defaultStyleValues['borderBottomWidth']); + $this->setBorderLeftWidth(self::$defaultStyleValues['borderLeftWidth']); + $this->setBorderColour(self::$defaultStyleValues['borderColour']); + } + + public function hasChangedFromDefaults() : bool + { + $currentValues = [ + $this->fg, + $this->bg, + $this->width, + $this->paddingTopBottom, + $this->paddingLeftRight, + $this->margin, + $this->itemExtra, + $this->displaysExtra, + $this->titleSeparator, + $this->borderTopWidth, + $this->borderRightWidth, + $this->borderBottomWidth, + $this->borderLeftWidth, + $this->borderColour, + $this->marginAuto, + ]; + + $defaultStyleValues = self::$defaultStyleValues; + if ($this->width !== $this->requestedWidth) { + $defaultStyleValues['width'] = $this->width; + } + + return $currentValues !== array_values($defaultStyleValues); + } + + /** + * Get text for a disabled menu item. + * + * This sets the foreground colour to the ansi bright equivalent, + * and on supported terminals, adds additional dim formatting. + * + * @return string + */ + public function getDisabledItemText(string $text) : string + { + return sprintf( + "\033[%sm\033[%sm%s\033[%sm\033[%sm", + self::$availableOptions['dim']['set'], + $this->getForegroundColourCode(true), + $text, + $this->getForegroundColourCode(), + self::$availableOptions['dim']['unset'] + ); + } + + /** + * Get the ansi escape sequence for the foreground colour. + * + * @param bool $bright Whether to modify to the ansi bright variation + * + * @return string + */ + private function getForegroundColourCode(bool $bright = false) : string + { + if (!ctype_digit($this->fg)) { + $fgCode = (int)self::$availableForegroundColors[$this->fg]; + $fgCode += ($bright ? 60 : 0); + } else { + $fgCode = sprintf("38;5;%s", ((int)$this->fg + ($bright ? 60 : 0))); + } + + return (string)$fgCode; + } + + /** + * Get the ansi escape sequence for the background colour. + * + * @param bool $bright Whether to modify to the ansi bright variation + * + * @return string + */ + private function getBackgroundColourCode(bool $bright = false) : string + { + if (!ctype_digit($this->bg)) { + $bgCode = (int)self::$availableBackgroundColors[$this->bg]; + $bgCode += ($bright ? 60 : 0); + } else { + $bgCode = sprintf("48;5;%s", ((int)$this->bg + ($bright ? 60 : 0))); + } + + return (string)$bgCode; + } + + /** + * Generates the ansi escape sequence to set the colours + */ + private function generateColoursSetCode() : void + { + $this->coloursSetCode = sprintf( + "\033[%s;%sm", + $this->getForegroundColourCode(), + $this->getBackgroundColourCode() + ); + } + + /** + * Get the colour code for Bg and Fg + */ + public function getColoursSetCode() : string + { + return $this->coloursSetCode; + } + + /** + * Get the inverted escape sequence (used for selected elements) + */ + public function getInvertedColoursSetCode() : string + { + return $this->invertedColoursSetCode; + } + + /** + * Get the inverted escape sequence (used for selected elements) + */ + public function getInvertedColoursUnsetCode() : string + { + return $this->invertedColoursUnsetCode; + } + + /** + * Get the escape sequence used to reset colours to default + */ + public function getColoursResetCode() : string + { + return $this->coloursResetCode; + } + + /** + * Calculate the contents width + * + * The content width is menu width minus borders and padding. + */ + protected function calculateContentWidth() : void + { + $this->contentWidth = $this->width + - ($this->paddingLeftRight * 2) + - ($this->borderRightWidth + $this->borderLeftWidth); + + if ($this->contentWidth < 0) { + $this->contentWidth = 0; + } + } + + public function getFg() : string + { + return $this->fg; + } + + public function setFg(string $fg, string $fallback = null) : self + { + $this->fg = ColourUtil::validateColour( + $this->terminal, + $fg, + $fallback + ); + $this->generateColoursSetCode(); + + return $this; + } + + public function getBg() : string + { + return $this->bg; + } + + public function setBg(string $bg, string $fallback = null) : self + { + $this->bg = ColourUtil::validateColour( + $this->terminal, + $bg, + $fallback + ); + + $this->generateColoursSetCode(); + $this->generatePaddingTopBottomRows(); + + return $this; + } + + public function getWidth() : int + { + return $this->width; + } + + public function setWidth(int $width) : self + { + Assertion::greaterOrEqualThan($width, 0); + + $this->requestedWidth = $width; + + $this->width = $this->maybeShrinkWidth($this->marginAuto ? 0 : $this->margin, $width); + + if ($this->marginAuto) { + $this->calculateMarginAuto($this->width); + } + + $this->calculateContentWidth(); + $this->generateBorderRows(); + $this->generatePaddingTopBottomRows(); + + return $this; + } + + private function maybeShrinkWidth(int $margin, int $width) : int + { + if ($width + ($margin * 2) >= $this->terminal->getWidth()) { + $width = $this->terminal->getWidth() - ($margin * 2); + + if ($width <= 0) { + throw CannotShrinkMenuException::fromMarginAndTerminalWidth($margin, $this->terminal->getWidth()); + } + } + + return $width; + } + + public function getPaddingTopBottom() : int + { + return $this->paddingTopBottom; + } + + public function getPaddingLeftRight() : int + { + return $this->paddingLeftRight; + } + + private function generatePaddingTopBottomRows() : void + { + if ($this->borderLeftWidth || $this->borderRightWidth) { + $borderColour = $this->getBorderColourCode(); + } else { + $borderColour = ''; + } + + $paddingRow = sprintf( + "%s%s%s%s%s%s%s%s%s%s\n", + $this->debugMode ? $this->getDebugString($this->margin) : str_repeat(' ', $this->margin), + $borderColour, + str_repeat(' ', $this->borderLeftWidth), + $this->getColoursSetCode(), + str_repeat(' ', $this->paddingLeftRight), + str_repeat(' ', $this->contentWidth), + str_repeat(' ', $this->paddingLeftRight), + $borderColour, + str_repeat(' ', $this->borderRightWidth), + $this->coloursResetCode + ); + + + if ($this->debugMode && s::length($paddingRow) <= $this->terminal->getWidth()) { + $paddingRow = substr_replace( + $paddingRow, + sprintf("%s\n", $this->getDebugString($this->terminal->getWidth() - (s::length($paddingRow) - 1))), + -1 + ); + } + + $this->paddingTopBottom = max($this->paddingTopBottom, 0); + $this->paddingTopBottomRows = array_fill(0, $this->paddingTopBottom, $paddingRow); + } + + /** + * @return array + */ + public function getPaddingTopBottomRows() : array + { + return $this->paddingTopBottomRows; + } + + public function setPadding(int $topBottom, int $leftRight = null) : self + { + if ($leftRight === null) { + $leftRight = $topBottom; + } + + $this->setPaddingTopBottom($topBottom); + $this->setPaddingLeftRight($leftRight); + + $this->calculateContentWidth(); + $this->generatePaddingTopBottomRows(); + + return $this; + } + + public function setPaddingTopBottom(int $topBottom) : self + { + Assertion::greaterOrEqualThan($topBottom, 0); + $this->paddingTopBottom = $topBottom; + + $this->generatePaddingTopBottomRows(); + + return $this; + } + + public function setPaddingLeftRight(int $leftRight) : self + { + Assertion::greaterOrEqualThan($leftRight, 0); + $this->paddingLeftRight = $leftRight; + + $this->calculateContentWidth(); + $this->generatePaddingTopBottomRows(); + + return $this; + } + + public function getMargin() : int + { + return $this->margin; + } + + public function setMarginAuto() : self + { + $this->marginAuto = true; + $this->margin = 0; + + $this->setWidth($this->requestedWidth); + + return $this; + } + + private function calculateMarginAuto(int $width) : void + { + $this->margin = (int) floor(($this->terminal->getWidth() - ($width)) / 2); + } + + public function setMargin(int $margin) : self + { + Assertion::greaterOrEqualThan($margin, 0); + + $this->marginAuto = false; + $this->margin = $margin; + + //margin + width may now exceed terminal size + //so set width again to trigger width check + maybe resize + $this->setWidth($this->requestedWidth); + + return $this; + } + + public function getContentWidth() : int + { + return $this->contentWidth; + } + + /** + * Get padding for right had side of content + */ + public function getRightHandPadding(int $contentLength) : int + { + $rightPadding = $this->getContentWidth() - $contentLength + $this->getPaddingLeftRight(); + + if ($rightPadding < 0) { + $rightPadding = 0; + } + + return $rightPadding; + } + + public function setItemExtra(string $itemExtra) : self + { + $this->itemExtra = $itemExtra; + + return $this; + } + + public function getItemExtra() : string + { + return $this->itemExtra; + } + + public function getDisplaysExtra() : bool + { + return $this->displaysExtra; + } + + public function setDisplaysExtra(bool $displaysExtra) : self + { + $this->displaysExtra = $displaysExtra; + + return $this; + } + + public function getTitleSeparator() : string + { + return $this->titleSeparator; + } + + public function setTitleSeparator(string $actionSeparator) : self + { + $this->titleSeparator = $actionSeparator; + + return $this; + } + + private function generateBorderRows() : void + { + $borderRow = sprintf( + "%s%s%s%s\n", + $this->debugMode ? $this->getDebugString($this->margin) : str_repeat(' ', $this->margin), + $this->getBorderColourCode(), + str_repeat(' ', $this->width), + $this->getColoursResetCode() + ); + + if ($this->debugMode && s::length($borderRow) <= $this->terminal->getWidth()) { + $borderRow = substr_replace( + $borderRow, + sprintf("%s\n", $this->getDebugString($this->terminal->getWidth() - (s::length($borderRow) - 1))), + -1 + ); + } + + $this->borderTopWidth = max($this->borderTopWidth, 0); + $this->borderBottomWidth = max($this->borderBottomWidth, 0); + + $this->borderTopRows = array_fill(0, $this->borderTopWidth, $borderRow); + $this->borderBottomRows = array_fill(0, $this->borderBottomWidth, $borderRow); + } + + /** + * @return array + */ + public function getBorderTopRows() : array + { + return $this->borderTopRows; + } + + /** + * @return array + */ + public function getBorderBottomRows() : array + { + return $this->borderBottomRows; + } + + /** + * @param int|string|null $rightWidth + * @param int|string|null $bottomWidth + * @param int|string|null $leftWidth + * + * Shorthand function to set all borders values at once + */ + public function setBorder( + int $topWidth, + $rightWidth = null, + $bottomWidth = null, + $leftWidth = null, + string $colour = null + ) : self { + if (!is_int($rightWidth)) { + $colour = $rightWidth; + $rightWidth = $bottomWidth = $leftWidth = $topWidth; + } elseif (!is_int($bottomWidth)) { + $colour = $bottomWidth; + $bottomWidth = $topWidth; + $leftWidth = $rightWidth; + } elseif (!is_int($leftWidth)) { + $colour = $leftWidth; + $leftWidth = $rightWidth; + } + + $this->borderTopWidth = $topWidth; + $this->borderRightWidth = $rightWidth; + $this->borderBottomWidth = $bottomWidth; + $this->borderLeftWidth = $leftWidth; + + if (is_string($colour)) { + $this->setBorderColour($colour); + } + + $this->calculateContentWidth(); + $this->generateBorderRows(); + $this->generatePaddingTopBottomRows(); + + return $this; + } + + public function setBorderTopWidth(int $width) : self + { + $this->borderTopWidth = $width; + + $this->generateBorderRows(); + + return $this; + } + + public function setBorderRightWidth(int $width) : self + { + $this->borderRightWidth = $width; + $this->calculateContentWidth(); + + $this->generatePaddingTopBottomRows(); + + return $this; + } + + public function setBorderBottomWidth(int $width) : self + { + $this->borderBottomWidth = $width; + + $this->generateBorderRows(); + + return $this; + } + + public function setBorderLeftWidth(int $width) : self + { + $this->borderLeftWidth = $width; + $this->calculateContentWidth(); + + $this->generatePaddingTopBottomRows(); + + return $this; + } + + public function setBorderColour(string $colour, string $fallback = null) : self + { + $this->borderColour = ColourUtil::validateColour( + $this->terminal, + $colour, + $fallback + ); + + $this->generateBorderRows(); + $this->generatePaddingTopBottomRows(); + + return $this; + } + + public function getBorderTopWidth() : int + { + return $this->borderTopWidth; + } + + public function getBorderRightWidth() : int + { + return $this->borderRightWidth; + } + + public function getBorderBottomWidth() : int + { + return $this->borderBottomWidth; + } + + public function getBorderLeftWidth() : int + { + return $this->borderLeftWidth; + } + + public function getBorderColour() : string + { + return $this->borderColour; + } + + public function getBorderColourCode() : string + { + if (!ctype_digit($this->borderColour)) { + $borderColourCode = self::$availableBackgroundColors[$this->borderColour]; + } else { + $borderColourCode = sprintf("48;5;%s", $this->borderColour); + } + + return sprintf("\033[%sm", $borderColourCode); + } + + + /** + * Get ansi escape sequence for setting or unsetting the specified option code. + * + * @param string $string Option code (bold|dim|underscore|blink|reverse|conceal) + * @param bool $set Whether to set or unset the code + * + * @return string + */ + public function getOptionCode(string $string, bool $set = true): string + { + return sprintf("\033[%sm", self::$availableOptions[$string][$set ? 'set' : 'unset']); + } + + /** + * Get a string of given length consisting of 0-9 + * eg $length = 15 : 012345678901234 + */ + private function getDebugString(int $length) : string + { + $nums = []; + for ($i = 0, $j = 0; $i < $length; $i++, $j++) { + if ($j === 10) { + $j = 0; + } + + $nums[] = $j; + } + + return implode('', $nums); + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/README.md b/src/ncc/ThirdParty/php-school/cli-menu/README.md new file mode 100644 index 0000000..c366325 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/README.md @@ -0,0 +1,1473 @@ +

+ +

+ +

+ + + + + + + + + + + + + + + +

+ +--- +## Contents + + * [Minimum Requirements](#minimum-requirements) + * [Installation](#installation) + * [Upgrading](#upgrading) + * [Usage](#usage) + * [Quick Setup](#quick-setup) + * [Examples](#examples) + * [API](#api) + * [Appearance](#appearance) + * [Menu Title](#menu-title) + * [Colour](#colour) + * [Width](#width) + * [Padding](#padding) + * [Margin](#margin) + * [Borders](#borders) + * [Exit Button Text](#exit-button-text) + * [Remove Exit Button](#remove-exit-button) + * [Items](#appearance) + * [Selectable Item](#selectable-item) + * [Checkbox Item](#checkbox-item) + * [Radio Item](#radio-item) + * [Line Break Item](#line-break-item) + * [Static Item](#static-item) + * [Ascii Art Item](#ascii-art-item) + * [Sub Menu Item](#sub-menu-item) + * [Split Item](#split-item) + * [Disabling Items & Sub Menus](#disabling-items--sub-menus) + * [Item Markers](#item-markers) + * [Item Extra](#item-extra) + * [Menu Methods](#menu-methods) + * [Redrawing the Menu](#redrawing-the-menu) + * [Getting, Removing and Adding items](#getting-removing-and-adding-items) + * [Custom Control Mapping](#custom-control-mapping) + * [Item Keyboard Shortcuts](#item-keyboard-shortcuts) + * [Dialogues](#dialogues) + * [Flash](#flash) + * [Confirm](#confirm) + * [Inputs](#inputs) + * [Text](#text-input) + * [Number](#number-input) + * [Password](#password-input) + * [Custom Input](#custom-input) + * [Dialogues & Input Styling](#dialogues--input-styling) + * [Docs Translations](#docs-translations) + * [Integrations](#integrations) + +## Minimum Requirements + + * PHP 7.1 + * Composer + * ext-posix + +## Installation + +```bash +composer require php-school/cli-menu +``` + +## Upgrading + +Please refer to the [Upgrade Documentation](UPGRADE.md) documentation to see what is required to upgrade your installed +`cli-menu` version. + +## Usage + +### Quick Setup +Here is a super basic example menu which will echo out the text of the selected item to get you started. +```php +getSelectedItem()->getText(); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('Basic CLI Menu') + ->addItem('First Item', $itemCallable) + ->addItem('Second Item', $itemCallable) + ->addItem('Third Item', $itemCallable) + ->addLineBreak('-') + ->setBorder(1, 2, 'yellow') + ->setPadding(2, 4) + ->setMarginAuto() + ->build(); + + +$menu->open(); +``` + +### Examples + +Check out the [examples](examples) directory and run them to see what is possible! The best way to run the examples is to git clone the repository: + +```shell +git clone https://github.com/php-school/cli-menu.git +cd cli-menu +composer install --no-dev +cd examples +php basic.php +``` + +#### Basic Menu +basic + +#### Basic Menu Auto Centered +submenu + +#### Basic Menu with separation +basic-seperation + +#### Menu with crazy separation +crazy-seperation + +#### Custom Styles +custom-styles + +#### Borders and 256 colours +submenu + +#### Useful Separation +useful-seperation + +#### Displaying Item Extra +item-extra + +#### Remove Defaults +remove-defaults + +#### Submenu +submenu +submenu-options + +#### Split Item +split-item + +#### Disabled Items & Submenus +submenu + +#### Checkbox Items +checkbox +checkbox-split + +#### Radio Items + +radio +radio-split + +#### Flash Dialogue +submenu + +#### Confirm Dialogue +submenu + +#### Number Input +submenu +submenu + +#### Text Input +submenu + +#### Password Input +submenu + +#### Using cli-menu to create art + +Want to see something really cool? Well you can use cli-menu to create a drawing canvas on your terminal. Check it out!: + +submenu + +## API + +The `CliMenu` object is constructed via the Builder class + +```php +build(); +``` + +Once you have a menu object, you can open and close it like so: + +```php +$menu->open(); +$menu->close(); +``` + +### Appearance + +#### Menu Title + +You can give your menu a title and you can customise the separator, a line which displays under the title. +Whatever string you pass to `setTitleSeparator` will be repeated for the width of the Menu. + +```php +setTitle('One Menu to rule them all!') + ->setTitleSeparator('*-') + ->build(); +``` + +#### Colour + +You can change the foreground and background colour of the menu to any of the following colours: + +* black +* red +* green +* yellow +* blue +* magenta +* cyan +* white + +```php +setForegroundColour('green') + ->setBackgroundColour('black') + ->build(); +``` + +If your terminal supports 256 colours then you can also use any of those by specifying the code, like `230`. You can find a list +of the [colours and codes here](https://jonasjacek.github.io/colors/). If you specify a code and the terminal does not support 256 colours +it will automatically fallback to a sane default, using a generated map you can see in src/Util/ColourUtil.php. You can also manually specify the +fallback colour as the second argument to `setForegroundColour` and `setBackgroundColour. + +In this example if no 256 colour support is found it will automatically fall back to `green` and `blue`. + +```php +setForegroundColour('40') + ->setBackgroundColour('92') + ->build(); +``` + +In this example if no 256 colour support is found it will fall back to `yellow` and `magenta`. + +```php +setForegroundColour('40', 'yellow') + ->setBackgroundColour('92', 'magenta') + ->build(); +``` + +#### Width + +Customise the width of the menu. Setting a value larger than the size of the terminal will result in +the width being the same as the terminal size. The width will include the padding and the border. So with a width of 100 +and all around border of 5 and all around padding of 5 will leave for a content width of 80 (5 + 5 + 80 + 5 + 5). + +```php +setWidth(1000) //if terminal is only 400, width will also be 400 + ->build(); +``` + +If you want to use the full width of the terminal, you can grab the terminal object and ask/set it from there like so: + +```php +setWidth($builder->getTerminal()->getWidth()) + ->build(); +``` + +If you want to use the full width of the terminal and apply a margin, use the terminal width, and we will do the calculations +automatically (shrink the width based on the margin). + +```php +setWidth($builder->getTerminal()->getWidth()) + ->setMargin(2) + ->build(); +``` + +#### Padding + +The padding can be set for all sides with one value or can be set individually for top/bottom and left/right. + +```php +setPadding(10) //10 padding top/bottom/left/right + ->build(); +``` + +Different values can also be set for the top/bottom and the left/right padding: + +```php +setPaddingTopBottom(10) + ->setPaddingLeftRight(5) + ->build(); +``` + +Configure top/bottom and left/right padding using the shorthand method: + +```php +setPadding(10, 5) //top/bottom = 10, left/right = 5 + ->build(); +``` + +#### Margin + +The margin can be customised as one value. It can also be set automatically which will center the menu nicely in the +terminal. + +Automatically center menu: + +```php +setWidth(200) + ->setMarginAuto() + ->build(); +``` + +Arbitrary margin: + +```php +setWidth(200) + ->setMargin(5) + ->build(); +``` + +#### Borders + +Borders can be customised just like CSS borders. We can add any amount of border to either side, left, right top or +bottom and we can apply a colour to it. + +Set universal red border of 2: + +```php +setWidth(200) + ->setBorder(2, 'red') + ->build(); +``` + +Configure each border separately: + +```php +setWidth(200) + ->setBorderTopWidth(2) + ->setBorderRightWidth(4) + ->setBorderBottomWidth(2) + ->setBorderLeftWidth(4) + ->setBorderColour('42', 'red') //SpringGreen2 fallback to red + ->build(); +``` + +Configure each border separately using the shorthand method, like CSS: + +```php +setWidth(200) + ->setBorder(3, 4, 'red') //top/bottom = 3, left/right = 4 + ->setBorder(3, 4, 5, 'red') //top = 3, left/right = 4, bottom = 5 + ->setBorder(3, 4, 5, 6, 'red') //top = 3, left = 4, bottom = 5, right = 6 + ->build(); +``` + +#### Exit Button Text + +Modify the exit button text: + +```php +setExitButtonText("Don't you want me baby?") + ->build(); +``` + +#### Remove Exit Button + +You can remove the exit button altogether: + +```php +disableDefaultItems() + ->build(); +``` + +Note: This will also disable the Go Back button for sub menus. + +You can manually add exit and go back buttons using the following: + +```php +disableDefaultItems() + ->addSubMenu('Super Sub Menu', function (CliMenuBuilder $b) { + $b->disableDefaultItems() + ->setTitle('Behold the awesomeness') + ->addItem('Return to parent menu', new GoBackAction); //add a go back button + }) + ->addItem('Leave this place now !', new ExitAction) //add an exit button + ->build(); +``` + +### Items + +There a few different types of items you can add to your menu + +* Selectable Item - This is the type of item you need for something to be selectable (you can hit enter and it will invoke your callable) +* Checkbox Item - This is a checkbox type of item that keeps track of its toggled state to show a different marker. +* Radio Item - This is a radio type of item that keeps track of its toggled state to show a different marker. Disables all other radios within its `CliMenu` level. +* Line Break Item - This is used to break up areas, it can span multiple lines and will be the width of Menu. Whatever string is passed will be repeated. +* Static Item - This will print whatever text is passed, useful for headings. +* Ascii Art Item - Special item which allows usage of Ascii art. It takes care of padding and alignment. +* Sub Menu Item - Special item to allow an item to open another menu. Useful for an options menu. +* Split Item - Special item to fit multiple items on the same row. + +### Selectable Item + +```php +addItem('The Item Text', function (CliMenu $menu) { + echo 'I am alive!'; + }) + ->build(); +``` + +You can add multiple items at once like so: + +```php +addItems([ + ['Item 1', $callable], + ['Item 2', $callable], + ['Item 3', $callable], + ]) + ->build(); +``` + +Note: You can add as many items as you want and they can all have a different action. The action is the second parameter +and must be a valid PHP `callable`. Try using an `Invokable` class to keep your actions easily testable. + +### Checkbox Item + +```php +getSelectedItem()->getText(); +}; + +$menu = (new CliMenuBuilder) + ->addCheckboxItem('Item 1', $callable) + ->addCheckboxItem('Item 2', $callable) + ->addCheckboxItem('Item 3', $callable) + ->build(); +``` + +You can add multiple checkbox items at once like so: + +```php +addCheckboxItems([ + ['Item 1', $callable], + ['Item 2', $callable], + ['Item 3', $callable], + ]) + ->build(); +``` + +When selecting an item, it will be toggled. Notice at first each item is unchecked. After selecting one it will become +checked. + +### Radio Item + +```php +getSelectedItem()->getText(); +}; + +$menu = (new CliMenuBuilder) + ->addRadioItem('Item 1', $callable) + ->addRadioItem('Item 2', $callable) + ->addRadioItem('Item 3', $callable) + ->build(); +``` + +You can add multiple radio items at once like so: + +```php +addRadioItems([ + ['Item 1', $callable], + ['Item 2', $callable], + ['Item 3', $callable], + ]) + ->build(); +``` + +When selecting an item, it will be toggled. Notice at first each item is unchecked. After selecting one it will become +checked and all other `RadioItem` within the same level will be unchecked. + +### Line Break Item + +```php +addLineBreak('<3', 2) + ->build(); +``` + +The above would repeat the character sequence `<3` across the Menu for 2 lines + +### Static Item + +Static items are similar to Line Breaks, however, they don't repeat and fill. It is output as is. +If the text is longer than the width of the Menu, it will be continued on the next line. + +```php +addStaticItem('AREA 1') + //add some items here + ->addStaticItem('AREA 2') + //add some boring items here + ->addStaticItem('AREA 51') + //add some top secret items here + ->build(); +``` + +### Ascii Art Item + +The following will place the Ascii art in the centre of your menu. Use these constants to alter the +alignment: + +* AsciiArtItem::POSITION_CENTER +* AsciiArtItem::POSITION_LEFT +* AsciiArtItem::POSITION_RIGHT + +```php +addAsciiArt($art, AsciiArtItem::POSITION_CENTER) + ->build(); +``` + +The third optional parameter to `addAsciiArt` is alternate text. If the ascii art is too wide for the terminal, then +it will not be displayed at all. However, if you pass a string to the third argument, in the case that the ascii art is too +wide for the terminal the alternate text will be displayed instead. + +### Sub Menu Item + +Sub Menus are really powerful! You can add Menus to Menus, whattttt?? You can have your main menu and then an options menu. +The options item will look like a normal item except when you hit it, you will enter to another menu, which +can have different styles and colours! + +```php +addItem('Normal Item', $callable) + ->addSubMenu('Super Sub Menu', function (CliMenuBuilder $b) { + $b->setTitle('Behold the awesomeness') + ->addItem(/** **/); + }) + ->build(); +``` + +In this example a single sub menu will be created. Upon entering the sub menu, you will be able to return to the main menu +or exit completely. A Go Back button will be automatically added. You can customise this text using the `->setGoBackButtonText()` method on the `CliMenuBuilder` +instance for the sub menu. + +There are a few things to note about the syntax and builder process here + +1. The first parameter to `addSubMenu` is the text to be displayed on the menu which you select to enter the submenu. +2. The second parameter is a closure, which will be invoked with a new instance of `CliMenuBuilder` which you can use to customise the sub menu exactly the same way you would the parent +3. If you do not modify the styles of the sub menu (eg, colours) it will inherit styles from the parent! + +If you have already have a configured menu builder you can just pass that to `addSubMenuFromBuilder` and be done: + +```php +setTitle('Behold the awesomeness') + ->addItem(/** **/); + +$menu = (new CliMenuBuilder) + ->addSubMenuFromBuilder('Super Sub Menu', $subMenuBuilder) + ->build(); +``` + +Note: The submenu menu item will be an instance of `\PhpSchool\CliMenu\MenuItem\MenuMenuItem`. If you need access to the submenu, +you can get it via `$menuMenuItem->getSubMenu()`. + +### Split Item + +Split Items allows you to add multiple items on the same row. The full width of the menu will be split evenly between all items. You can move between those items using left/right arrows. + +You can set the number of spaces separating items using `->setGutter()` (defaults to 2). + +Only Selectable, Checkbox, Radio, Static and SubMenu items are currently allowed inside a Split Item. + +```php +getSelectedItem()->getText(); +}; + +$menu = (new CliMenuBuilder) + ->setWidth(150) + ->addStaticItem('Below is a SplitItem') + ->addSplitItem(function (SplitItemBuilder $b) use ($itemCallable) { + $b->setGutter(5) + ->addSubMenu('Sub Menu on a split item', function (CliMenuBuilder $b) { + $b->setTitle('Behold the awesomeness') + ->addItem('This is awesome', function() { print 'Yes!'; }); + }) + ->addItem('Item 2', $itemCallable) + ->addStaticItem('Item 3 - Static'); + }) + ->build(); + +$menu->open(); +``` + +There are a few things to note about the syntax and builder process here: + +1. The first parameter to `addSplitItem` is a closure, which will be invoked with a new instance of `SplitItemBuilder` which you can use to add items to the split item. +2. You can call `addItem`, `addCheckboxItem`, `addRadioItem`, `addSubMenu` and `addStaticItem` on the `SplitItemBuilder`. +3. `SplitItemBuilder` has a fluent interface so you can chain method calls. + +### Disabling Items & Sub Menus + +In this example we are disabling certain items and a submenu but still having them shown in the menu. + +```php +getSelectedItem()->getText(); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('Basic CLI Menu Disabled Items') + ->addItem('First Item', $itemCallable) + ->addItem('Second Item', $itemCallable, false, true) + ->addItem('Third Item', $itemCallable, false, true) + ->addSubMenu('Submenu', function (CliMenuBuilder $b) use ($itemCallable) { + $b->setTitle('Basic CLI Menu Disabled Items > Submenu') + ->addItem('You can go in here!', $itemCallable); + }) + ->addSubMenu('Disabled Submenu', function (CliMenuBuilder $b) use ($itemCallable) { + $b->setTitle('Basic CLI Menu Disabled Items > Disabled Submenu') + ->addItem('Nope can\'t see this!', $itemCallable) + ->disableMenu(); + }) + ->addLineBreak('-') + ->build(); +``` + +The third param on the `->addItem` call is what disables an item while the `->disableMenu()` call disables the relevant menu. + +The outcome is a full menu with dimmed rows to denote them being disabled. When a user navigates the menu these items are jumped over to the next available selectable item. + +### Item Markers + +The marker displayed by the side of the currently active item can be modified, UTF-8 characters are supported. +The marker for un-selected items can also be modified. If you want to disable it, just set it to an empty string. Item +markers only display on *selectable* items, which are: `\PhpSchool\CliMenu\MenuItem\SelectableItem` & `\PhpSchool\CliMenu\MenuItem\MenuMenuItem`. + +```php +modifySelectableStyle(function (SelectableStyle $style) { + $style->setUnselectedMarker('❅ ') + ->setSelectedMarker('✏ ') + + // disable unselected marker + ->setUnselectedMarker('') + ; + }) + ->build(); +``` + +You may also change the marker for `\PhpSchool\CliMenu\MenuItem\CheckboxItem`: + +```php +modifyCheckboxStyle(function (CheckboxStyle $style) { + $style->setUncheckedMarker('[○] ') + ->setCheckedMarker('[●] '); + }) + ->addCheckboxItem('Orange juice', function () {}) + ->addCheckboxItem('Bread', function () {}) + ->build(); +``` + +and for `\PhpSchool\CliMenu\MenuItem\RadioItem`: + +```php +modifyRadioStyle(function (RadioStyle $style) { + $style->setUncheckedMarker('[ ] ') + ->setCheckedMarker('[✔] '); + }) + ->addRadioItem('Go shopping', function () {}) + ->addRadioItem('Go camping', function () {}) + ->build(); +``` + +### Item Extra + +You can optionally display some arbitrary text on the right hand side of an item. You can customise this text and +you indicate which items to display it on. We use it to display `[COMPLETED]` on completed exercises, where the menu lists +exercises for a workshop application. + +Item Extra is currently limited to only selectable items (menus, checkboxes & radios included) + +The third parameter to `addItem` is a boolean whether to show the item extra or not. It defaults to false. + +```php +modifySelectableStyle(function (SelectableStyle $style) { + $style->setItemExtra('✔'); + }) + ->addItem('Exercise 1', function (CliMenu $menu) { echo 'I am complete!'; }, true) + ->build(); +``` + +If no items have display extra set to true, then the item extra will not be displayed. If you toggle the item to show +it's item extra in a callback or at runtime it will render incorrectly. + +In order to fix that you need to tell the menu to display item extra explicitly. You can do this when constructing the +menu like so: + +```php +setItemExtra('✔') + ->addItem('Exercise 1', function (CliMenu $menu) { + $selectedItem = $menu->getSelectedItem(); + if ($selectedItem->showsItemExtra()) { + $selectedItem->hideItemExtra(); + } else { + $selectedItem->showItemExtra(); + } + }) + ->displayExtra() + ->build(); +``` + +## Menu Methods + +The next set of documentation applies to methods available directly on the `\PhpSchool\CliMenu\CliMenu` instance. Typically +you will invoke these methods whilst your menu is open in you action callbacks. + +### Redrawing the Menu + +You can modify the menu and its style when executing an action and then you can redraw it! In this example we will toggle the background +colour in an action. + +```php +getStyle()->setBg($menu->getStyle()->getBg() === 'red' ? 'blue' : 'red'); + $menu->redraw(); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('Basic CLI Menu') + ->addItem('First Item', $itemCallable) + ->addItem('Second Item', $itemCallable) + ->addItem('Third Item', $itemCallable) + ->addLineBreak('-') + ->build(); + +$menu->open(); +``` + +If you change the menu drastically, such as making the width smaller, when it redraws you might see artifacts of the previous draw +as `redraw` only draws over the top of the terminal. If this happens you can pass `true` to `redraw` and it will first clear +the terminal before redrawing. + +```php +getStyle()->setWidth($menu->getStyle()->getWidth() === 100 ? 80 : 100); + $menu->redraw(true); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('Basic CLI Menu') + ->addItem('First Item', $itemCallable) + ->addItem('Second Item', $itemCallable) + ->addItem('Third Item', $itemCallable) + ->addLineBreak('-') + ->build(); + +$menu->open(); +``` + +### Getting, Removing and Adding items + +You can also interact with the menu items in an action. You can add, remove and replace items. If you do this, you +will likely want to redraw the menu as well so the new list is rendered. + +```php +getItems() as $item) { + $menu->removeItem($item); + } + + //add single item + $menu->addItem(new LineBreakItem('-')); + + //add multiple items + $menu->addItems([new LineBreakItem('-'), new LineBreakItem('*')]); + + //replace all items + $menu->setItems([new LineBreakItem('+'), new LineBreakItem('-')]); + + $menu->redraw(); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('Basic CLI Menu') + ->addItem('First Item', $itemCallable) + ->addItem('Second Item', $itemCallable) + ->addItem('Third Item', $itemCallable) + ->addLineBreak('-') + ->build(); + +$menu->open(); +``` + +## Custom Control Mapping + +This functionality allows to map custom key presses to a callable. For example we can set the key press "x" to close the menu: + +```php +close(); +}; + +$menu = (new CliMenuBuilder) + ->addItem('Item 1', function(CliMenu $menu) {}) + ->build(); + +$menu->addCustomControlMapping("x", $exit); + +$menu->open(); +``` + +Another example is mapping shortcuts to a list of items: + +```php +addItem('List of [C]lients', $myCallback) + ->build(); + +// Now, pressing Uppercase C (it's case sensitive) will call $myCallback +$menu->addCustomControlMapping('C', $myCallback); + +$menu->open(); +``` + +## Item Keyboard Shortcuts + +If you enable auto shortcuts `CliMenuBuilder` will parse the items text and check for shortcuts. Any single character inside square brackets +will be treated as a shortcut. Pressing that character when the menu is open will trigger that items callable. + +This functionality works for split items as well as sub menus. The same characters can be used inside sub menus and the +callable which is invoked will depend on which menu is currently open. + +Note: all shortcuts are lower cased. + +To enable this automatic keyboard shortcut mapping simply call `->enableAutoShortcuts()`: + +```php +enableAutoShortcuts() + ->addItem('List of [C]lients', $myCallback) + ->build(); + +$menu->open(); + +//Pressing c will execute $myCallback. +``` + +You can customise the shortcut matching by passing your own regex to `enableAutoShortcuts`. Be careful to only match +one character in the first capture group or an exception will be thrown. + +### Dialogues + +#### Flash + +Show a one line message over the top of the menu. It has a separate style object which is colored by default different +to the menu. It can be modified to suit your own style. The dialogue is dismissed with any key press. In the example +below we change the background color on the flash to green. + +```php +flash("PHP School FTW!!"); + $flash->getStyle()->setBg('green'); + $flash->display(); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('Basic CLI Menu') + ->addItem('First Item', $itemCallable) + ->addItem('Second Item', $itemCallable) + ->addItem('Third Item', $itemCallable) + ->addLineBreak('-') + ->build(); + +$menu->open(); +``` + +#### Confirm + +Prompts are very similar to flashes except that a button is shown which has to be selected to dismiss them. The button +text can be customised. + +```php +confirm('PHP School FTW!') + ->display('OK!'); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('Basic CLI Menu') + ->addItem('First Item', $itemCallable) + ->addItem('Second Item', $itemCallable) + ->addItem('Third Item', $itemCallable) + ->addLineBreak('-') + ->build(); + +$menu->open(); +``` +### Inputs + +Inputs - added in version 3.0 of `cli-menu` allow to prompt the user for input and validate it. The following types are supported: +text, number and password. Inputs can be executed in any item callback. They have separate style objects which are colored by default different to the menu. +They can be modified to suit your own style. + +Each input is created by calling one of the `ask*` methods which will return an +instance of the input you requested. To execute the prompt and wait for the input you must +call `ask()` on the input. When the input has been received and validated, `ask()` will return +an instance of `InputResult`. `InputResult` exposes the method `fetch` to grab the raw input. + +#### Text Input + +The text input will prompt for a string and when the enter key is hit it will validate that +the string is not empty. As well as the style you can modify the prompt text (the default is 'Enter text:'), the +placeholder text (the default is empty) and the validation failed text (the default is 'Invalid, try again'). + +```php +askText() + ->setPromptText('Enter your name') + ->setPlaceholderText('Jane Doe') + ->setValidationFailedText('Please enter your name') + ->ask(); + + var_dump($result->fetch()); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('Basic CLI Menu') + ->addItem('Enter text', $itemCallable) + ->addLineBreak('-') + ->build(); + +$menu->open(); + +``` + +#### Number Input + +The number input will prompt for an integer value (signed or not) and when the enter key is hit it will validate that +the input is actually a number (`/^-?\d+$/`). As well as the style you can modify the prompt text (the default is 'Enter a number:'), the +placeholder text (the default is empty) and the validation failed text (the default is 'Not a valid number, try again'). + +When entering a number you can use the up/down keys to increment and decrement the number. + +```php +askNumber() + ->setPromptText('Enter your age') + ->setPlaceholderText(10) + ->setValidationFailedText('Invalid age, try again') + ->ask(); + + var_dump($result->fetch()); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('Basic CLI Menu') + ->addItem('Enter number', $itemCallable) + ->addLineBreak('-') + ->build(); + +$menu->open(); + +``` + +#### Password Input + +The password input will prompt for a text value and when the enter key is hit it will validate that the input is 16 characters or longer. +As well as the style you can modify the prompt text (the default is 'Enter password:'), the +placeholder text (the default is empty) and the validation failed text (the default is 'Invalid password, try again'). You can also set +a custom password validator as a PHP callable. When typing passwords they are echo'd back to the user as an asterisk. + +Ask for a password with the default validation: + +```php +askPassword() + ->setPromptText('Please enter your password') + ->setValidationFailedText('Invalid password, try again') + ->setPlaceholderText('') + ->ask(); + + var_dump($result->fetch()); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('Basic CLI Menu') + ->addItem('Enter password', $itemCallable) + ->addLineBreak('-') + ->build(); + +$menu->open(); + +``` + +Validators can be any PHP callable. The callable will be passed the input value and must return a boolean, false indicating +validation failure and true indicating validation success. If validation fails then the validation failure text will be shown. + +It is also possible to customise the validation failure message dynamically, but only when using a `Closure` as a validator. +The closure will be binded to the `Password` input class which will allow you to call `setValidationFailedText` inside the closure. + +Ask for a password with custom validation. Here we validate the password is not equal to `password` and that the +password is longer than 20 characters. + +```php +askPassword() + ->setPromptText('Please enter your password') + ->setValidationFailedText('Invalid password, try again') + ->setPlaceholderText('') + ->setValidator(function ($password) { + return $password !== 'password' && strlen($password) > 20; + }) + ->ask(); + + var_dump($result->fetch()); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('Basic CLI Menu') + ->addItem('Enter password', $itemCallable) + ->addLineBreak('-') + ->build(); + +$menu->open(); + +``` + +Ask for a password with custom validation and set the validation failure message dynamically: + +```php +askPassword() + ->setPromptText('Please enter your password') + ->setValidationFailedText('Invalid password, try again') + ->setPlaceholderText('') + ->setValidator(function ($password) { + if ($password === 'password') { + $this->setValidationFailedText('Password is too weak'); + return false; + } else if (strlen($password) <= 20) { + $this->setValidationFailedText('Password is not long enough'); + return false; + } + + return true; + }) + ->ask(); + + var_dump($result->fetch()); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('Basic CLI Menu') + ->addItem('Enter password', $itemCallable) + ->addLineBreak('-') + ->build(); + +$menu->open(); + +``` + +#### Custom Input + +If you need a new type of input which is not covered by the bundled selection then you can create your own by implementing +`\PhpSchool\CliMenu\Input\Input` - take a look at existing implementations to see how they are built. If all you need is some custom +validation - extend the `\PhpSchool\CliMenu\Input\Text` class and overwrite the `validate` method. You can then use it in +your menu item actions like so: + +```php +setBg('yellow') + ->setFg('black'); + + $input = new class (new InputIO($menu, $menu->getTerminal()), $style) extends Text { + public function validate(string $value) : bool + { + //some validation + return true; + } + }; + + $result = $input->ask(); + + var_dump($result->fetch()); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('Basic CLI Menu') + ->addItem('Enter password', $itemCallable) + ->addLineBreak('-') + ->build(); + +$menu->open(); + +``` + +### Dialogues & Input Styling + +All of the dialogues and inputs expose a `getStyle()` method which you can use to customise the appearance of them. However, if +you want to create a consistent style for all your dialogues and inputs without configuring it for each one +you can build up a `MenuStyle` object and pass it to the dialogue and input methods like so: + +```php +setBg('green') + ->setFg('magenta'); + +$itemCallable = function (CliMenu $menu) use ($popupStyle) { + $menu->flash("PHP School FTW!!", $popupStyle)->display(); + $menu->confirm('PHP School FTW!', $popupStyle)->display('OK!'); + $menu->askNumber($popupStyle)->ask(); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('Basic CLI Menu') + ->addItem('First Item', $itemCallable) + ->addItem('Second Item', $itemCallable) + ->addItem('Third Item', $itemCallable) + ->addLineBreak('-') + ->build(); + +$menu->open(); +``` + +--- + +Once you get going you might just end up with something that looks a little like this... + +![Learn You PHP CLI Menu](https://cloud.githubusercontent.com/assets/2174476/11409864/be082444-93ba-11e5-84ab-1b6cfa38aef8.png) + +You can see the construction code here for more clarity on how to perform advanced configuration: +[PHP School](https://github.com/php-school/php-workshop/blob/3240d3217bbf62b1063613fc13eb5adff2299bbe/src/Factory/MenuFactory.php) + +## Integrations + + * [Symfony Console](https://github.com/RedAntNL/console) + * [Laravel](https://github.com/nunomaduro/laravel-console-menu) + * [Laravel Artisan](https://github.com/VladReshet/ArtisanUI) diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Style/CheckboxStyle.php b/src/ncc/ThirdParty/php-school/cli-menu/Style/CheckboxStyle.php new file mode 100644 index 0000000..a3bc34e --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Style/CheckboxStyle.php @@ -0,0 +1,119 @@ + '[✔] ', + 'uncheckedMarker' => '[ ] ', + 'itemExtra' => '✔', + 'displaysExtra' => false, + ]; + + /** + * @var string + */ + private $checkedMarker; + + /** + * @var string + */ + private $uncheckedMarker; + + /** + * @var string + */ + private $itemExtra; + + /** + * @var bool + */ + private $displaysExtra; + + public function __construct() + { + $this->checkedMarker = self::DEFAULT_STYLES['checkedMarker']; + $this->uncheckedMarker = self::DEFAULT_STYLES['uncheckedMarker']; + $this->itemExtra = self::DEFAULT_STYLES['itemExtra']; + $this->displaysExtra = self::DEFAULT_STYLES['displaysExtra']; + } + + public function hasChangedFromDefaults() : bool + { + $currentValues = [ + $this->checkedMarker, + $this->uncheckedMarker, + $this->itemExtra, + $this->displaysExtra, + ]; + + return $currentValues !== array_values(self::DEFAULT_STYLES); + } + + public function getMarker(MenuItemInterface $item, bool $selected) : string + { + if (!$item instanceof CheckboxItem) { + throw new \InvalidArgumentException( + sprintf('Expected an instance of: %s. Got: %s', CheckboxItem::class, get_class($item)) + ); + } + + return $item->getChecked() ? $this->checkedMarker : $this->uncheckedMarker; + } + + public function getCheckedMarker() : string + { + return $this->checkedMarker; + } + + public function setCheckedMarker(string $marker) : self + { + $this->checkedMarker = $marker; + + return $this; + } + + public function getUncheckedMarker() : string + { + return $this->uncheckedMarker; + } + + public function setUncheckedMarker(string $marker) : self + { + $this->uncheckedMarker = $marker; + + return $this; + } + + public function getItemExtra() : string + { + return $this->itemExtra; + } + + public function setItemExtra(string $itemExtra) : self + { + $this->itemExtra = $itemExtra; + + // if we customise item extra, it means we most likely want to display it + $this->setDisplaysExtra(true); + + return $this; + } + + public function getDisplaysExtra() : bool + { + return $this->displaysExtra; + } + + public function setDisplaysExtra(bool $displaysExtra) : self + { + $this->displaysExtra = $displaysExtra; + + return $this; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Style/DefaultStyle.php b/src/ncc/ThirdParty/php-school/cli-menu/Style/DefaultStyle.php new file mode 100644 index 0000000..7fe273a --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Style/DefaultStyle.php @@ -0,0 +1,30 @@ + DefaultStyle::class, + AsciiArtItem::class => DefaultStyle::class, + LineBreakItem::class => DefaultStyle::class, + SplitItem::class => DefaultStyle::class, + SelectableItem::class => SelectableStyle::class, + MenuMenuItem::class => SelectableStyle::class, + CheckboxItem::class => CheckboxStyle::class, + RadioItem::class => RadioStyle::class, + ]; + + /** + * @var array + */ + private $styles; + + public function __construct() + { + $this->styles = [ + DefaultStyle::class => new DefaultStyle(), + SelectableStyle::class => new SelectableStyle(), + CheckboxStyle::class => new CheckboxStyle(), + RadioStyle::class => new RadioStyle() + ]; + } + + /** + * For each of our unmodified item styles, we replace ours with the versions + * from the given style locator. + * + * @param Locator $other + */ + public function importFrom(self $other) : void + { + $this->styles = mapWithKeys( + $this->styles, + function ($styleClass, ItemStyle $instance) use ($other) { + return $instance->hasChangedFromDefaults() + ? $instance + : $other->getStyle($styleClass); + } + ); + } + + public function getStyle(string $styleClass) : ItemStyle + { + if (!isset($this->styles[$styleClass])) { + throw InvalidStyle::unregisteredStyle($styleClass); + } + + return $this->styles[$styleClass]; + } + + public function setStyle(ItemStyle $itemStyle, string $styleClass) : void + { + if (!isset($this->styles[$styleClass])) { + throw InvalidStyle::unregisteredStyle($styleClass); + } + + if (!$itemStyle instanceof $styleClass) { + throw InvalidStyle::notSubClassOf($styleClass); + } + + $this->styles[$styleClass] = $itemStyle; + } + + public function hasStyleForMenuItem(MenuItemInterface $item) : bool + { + return isset($this->itemStyleMap[get_class($item)]); + } + + public function getStyleForMenuItem(MenuItemInterface $item) : ItemStyle + { + if (!isset($this->itemStyleMap[get_class($item)])) { + throw InvalidStyle::unregisteredItem(get_class($item)); + } + + $styleClass = $this->itemStyleMap[get_class($item)]; + + return $this->getStyle($styleClass); + } + + public function registerItemStyle(string $itemClass, ItemStyle $itemStyle) : void + { + if (isset($this->itemStyleMap[$itemClass])) { + throw InvalidStyle::itemAlreadyRegistered($itemClass); + } + + $this->itemStyleMap[$itemClass] = get_class($itemStyle); + $this->styles[get_class($itemStyle)] = $itemStyle; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Style/RadioStyle.php b/src/ncc/ThirdParty/php-school/cli-menu/Style/RadioStyle.php new file mode 100644 index 0000000..d053f72 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Style/RadioStyle.php @@ -0,0 +1,119 @@ + '[●] ', + 'uncheckedMarker' => '[○] ', + 'itemExtra' => '✔', + 'displaysExtra' => false, + ]; + + /** + * @var string + */ + private $checkedMarker; + + /** + * @var string + */ + private $uncheckedMarker; + + /** + * @var string + */ + private $itemExtra; + + /** + * @var bool + */ + private $displaysExtra; + + public function __construct() + { + $this->checkedMarker = self::DEFAULT_STYLES['checkedMarker']; + $this->uncheckedMarker = self::DEFAULT_STYLES['uncheckedMarker']; + $this->itemExtra = self::DEFAULT_STYLES['itemExtra']; + $this->displaysExtra = self::DEFAULT_STYLES['displaysExtra']; + } + + public function hasChangedFromDefaults() : bool + { + $currentValues = [ + $this->checkedMarker, + $this->uncheckedMarker, + $this->itemExtra, + $this->displaysExtra, + ]; + + return $currentValues !== array_values(self::DEFAULT_STYLES); + } + + public function getMarker(MenuItemInterface $item, bool $selected) : string + { + if (!$item instanceof RadioItem) { + throw new \InvalidArgumentException( + sprintf('Expected an instance of: %s. Got: %s', RadioItem::class, get_class($item)) + ); + } + + return $item->getChecked() ? $this->checkedMarker : $this->uncheckedMarker; + } + + public function getCheckedMarker() : string + { + return $this->checkedMarker; + } + + public function setCheckedMarker(string $marker) : self + { + $this->checkedMarker = $marker; + + return $this; + } + + public function getUncheckedMarker() : string + { + return $this->uncheckedMarker; + } + + public function setUncheckedMarker(string $marker) : self + { + $this->uncheckedMarker = $marker; + + return $this; + } + + public function getItemExtra() : string + { + return $this->itemExtra; + } + + public function setItemExtra(string $itemExtra) : self + { + $this->itemExtra = $itemExtra; + + // if we customise item extra, it means we most likely want to display it + $this->setDisplaysExtra(true); + + return $this; + } + + public function getDisplaysExtra() : bool + { + return $this->displaysExtra; + } + + public function setDisplaysExtra(bool $displaysExtra) : self + { + $this->displaysExtra = $displaysExtra; + + return $this; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Style/SelectableStyle.php b/src/ncc/ThirdParty/php-school/cli-menu/Style/SelectableStyle.php new file mode 100644 index 0000000..3d7bd2f --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Style/SelectableStyle.php @@ -0,0 +1,112 @@ + '● ', + 'unselectedMarker' => '○ ', + 'itemExtra' => '✔', + 'displaysExtra' => false, + ]; + + /** + * @var string + */ + private $selectedMarker; + + /** + * @var string + */ + private $unselectedMarker; + + /** + * @var string + */ + private $itemExtra; + + /** + * @var bool + */ + private $displaysExtra; + + public function __construct() + { + $this->selectedMarker = self::DEFAULT_STYLES['selectedMarker']; + $this->unselectedMarker = self::DEFAULT_STYLES['unselectedMarker']; + $this->itemExtra = self::DEFAULT_STYLES['itemExtra']; + $this->displaysExtra = self::DEFAULT_STYLES['displaysExtra']; + } + + public function hasChangedFromDefaults() : bool + { + $currentValues = [ + $this->selectedMarker, + $this->unselectedMarker, + $this->itemExtra, + $this->displaysExtra, + ]; + + return $currentValues !== array_values(self::DEFAULT_STYLES); + } + + public function getMarker(MenuItemInterface $item, bool $selected) : string + { + return $selected ? $this->selectedMarker : $this->unselectedMarker; + } + + public function getSelectedMarker() : string + { + return $this->selectedMarker; + } + + public function setSelectedMarker(string $marker) : self + { + $this->selectedMarker = $marker; + + return $this; + } + + public function getUnselectedMarker() : string + { + return $this->unselectedMarker; + } + + public function setUnselectedMarker(string $marker) : self + { + $this->unselectedMarker = $marker; + + return $this; + } + + public function getItemExtra() : string + { + return $this->itemExtra; + } + + public function setItemExtra(string $itemExtra) : self + { + $this->itemExtra = $itemExtra; + + // if we customise item extra, it means we most likely want to display it + $this->setDisplaysExtra(true); + + return $this; + } + + public function getDisplaysExtra() : bool + { + return $this->displaysExtra; + } + + public function setDisplaysExtra(bool $displaysExtra) : self + { + $this->displaysExtra = $displaysExtra; + + return $this; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Terminal/TerminalFactory.php b/src/ncc/ThirdParty/php-school/cli-menu/Terminal/TerminalFactory.php new file mode 100644 index 0000000..1cb4e03 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Terminal/TerminalFactory.php @@ -0,0 +1,20 @@ + + */ +class TerminalFactory +{ + public static function fromSystem() : Terminal + { + return new UnixTerminal(new ResourceInputStream, new ResourceOutputStream); + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/UPGRADE.md b/src/ncc/ThirdParty/php-school/cli-menu/UPGRADE.md new file mode 100644 index 0000000..b46f485 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/UPGRADE.md @@ -0,0 +1,113 @@ +# Upgrade Documentation + +This document serves as a reference to upgrade your current cli-menu installation if improvements, deprecations +or backwards compatibility (BC) breakages occur. + +## 4.0.0 + +### BC breaks + +* Trait `PhpSchool\CliMenu\MenuItem\SelectableTrait` was removed. Copy the old code into your menu item + if you need it. +* Methods `PhpSchool\CliMenu\Builder\CliMenuBuilder#setUnselectedMarker()` & `PhpSchool\CliMenu\Builder\CliMenuBuilder#setSelectedMarker()` were removed. + Customise markers on the individual item styles: + + ```php + modifySelectableStyle(function (SelectableStyle $style) { + $style->setUnselectedMarker('❅ ') + ->setSelectedMarker('✏ ') + + // disable unselected marker + ->setUnselectedMarker('') + ; + }) + ->build(); + ``` +* Method getStyle() was added to interface PhpSchool\CliMenu\MenuItem\MenuItemInterface. Items must now implement this + method. For selectable items use `\PhpSchool\CliMenu\Style\SelectableStyle` or a subclass of. For static items use + `\PhpSchool\CliMenu\Style\DefaultStyle` or a subclass of. +* `PhpSchool\CliMenu\MenuStyle` marker methods have been removed. If you were using these directly. Operate on the item + style object instead. + +## 3.0.0 + +### BC breaks + +* Class `PhpSchool\CliMenu\CliMenuBuilder` has been moved, use + `PhpSchool\CliMenu\Builder\CliMenuBuilder` instead. Please migrate to the new namespace. +* `PhpSchool\CliMenu\Builder\CliMenuBuilder#addSubMenu` now takes a text and a closure used to configure the submenu. The callback + invoked with a new instance of `PhpSchool\CliMenu\Builder\CliMenuBuilder` as a parameter. `addSubMenu` now returns itself instead of + the sub menu `PhpSchool\CliMenu\Builder\CliMenuBuilder`. See below for upgrade example. +* Removed `PhpSchool\CliMenu\Terminal` namespace, the code has been migrated to the `php-school/terminal` package and is + largely modified. +* Removed methods `setTerminal`, `getSubMenu`, `getMenuStyle` and `end` from `PhpSchool\CliMenu\CliMenuBuilder`. +* Removed static method `getDefaultStyleValues` on `PhpSchool\CliMenu\MenuStyle`. + + +#### Migrating to new `addSubMenu` method in `CliMenuBuilder` + +Previous code: + +```php +getSelectedItem()->getText(); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('CLI Menu') + ->addItem('First Item', $itemCallable) + ->addLineBreak('-') + ->addSubMenu('Options') + ->setTitle('CLI Menu > Options') + ->addItem('First option', function (CliMenu $menu) { + echo sprintf('Executing option: %s', $menu->getSelectedItem()->getText()); + }) + ->addLineBreak('-') + ->end() + ->build(); + +$menu->open(); +``` + +Would now become: + +```php +getSelectedItem()->getText(); +}; + +$menu = (new CliMenuBuilder) + ->setTitle('CLI Menu') + ->addItem('First Item', $itemCallable) + ->addLineBreak('-') + ->addSubMenu('Options', function (CliMenuBuilder $b) { + $b->setTitle('CLI Menu > Options') + ->addItem('First option', function (CliMenu $menu) { + echo sprintf('Executing option: %s', $menu->getSelectedItem()->getText()); + }) + ->addLineBreak('-'); + }) + ->build(); + +$menu->open(); +``` diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Util/ArrayUtils.php b/src/ncc/ThirdParty/php-school/cli-menu/Util/ArrayUtils.php new file mode 100644 index 0000000..2e31c05 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Util/ArrayUtils.php @@ -0,0 +1,41 @@ + $v) { + $callback($k, $v); + } +} + +function max(array $items) : int +{ + return count($items) > 0 ? \max($items) : 0; +} + +function collect(array $items) : Collection +{ + return new Collection($items); +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Util/Collection.php b/src/ncc/ThirdParty/php-school/cli-menu/Util/Collection.php new file mode 100644 index 0000000..2e854c0 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Util/Collection.php @@ -0,0 +1,45 @@ +items = $items; + } + + public function map(callable $cb) : self + { + return new self(mapWithKeys($this->items, $cb)); + } + + public function filter(callable $cb) : self + { + return new self(filter($this->items, $cb)); + } + + public function values() : self + { + return new self(array_values($this->items)); + } + + public function each(callable $cb) : self + { + each($this->items, $cb); + + return $this; + } + + public function all() : array + { + return $this->items; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Util/ColourUtil.php b/src/ncc/ThirdParty/php-school/cli-menu/Util/ColourUtil.php new file mode 100644 index 0000000..03e34e6 --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Util/ColourUtil.php @@ -0,0 +1,334 @@ + 'black', + 1 => 'red', + 2 => 'green', + 3 => 'yellow', + 4 => 'blue', + 5 => 'magenta', + 6 => 'cyan', + 7 => 'white', + 8 => 'black', + 9 => 'red', + 10 => 'green', + 11 => 'yellow', + 12 => 'blue', + 13 => 'magenta', + 14 => 'cyan', + 15 => 'white', + 16 => 'black', + 17 => 'blue', + 18 => 'blue', + 19 => 'blue', + 20 => 'blue', + 21 => 'blue', + 22 => 'green', + 23 => 'cyan', + 24 => 'cyan', + 25 => 'blue', + 26 => 'blue', + 27 => 'blue', + 28 => 'green', + 29 => 'green', + 30 => 'cyan', + 31 => 'cyan', + 32 => 'blue', + 33 => 'blue', + 34 => 'green', + 35 => 'green', + 36 => 'green', + 37 => 'cyan', + 38 => 'cyan', + 39 => 'cyan', + 40 => 'green', + 41 => 'green', + 42 => 'green', + 43 => 'cyan', + 44 => 'cyan', + 45 => 'cyan', + 46 => 'green', + 47 => 'green', + 48 => 'green', + 49 => 'green', + 50 => 'cyan', + 51 => 'cyan', + 52 => 'red', + 53 => 'blue', + 54 => 'blue', + 55 => 'blue', + 56 => 'blue', + 57 => 'blue', + 58 => 'yellow', + 59 => 'black', + 60 => 'blue', + 61 => 'blue', + 62 => 'blue', + 63 => 'blue', + 64 => 'green', + 65 => 'green', + 66 => 'cyan', + 67 => 'cyan', + 68 => 'blue', + 69 => 'blue', + 70 => 'green', + 71 => 'green', + 72 => 'green', + 73 => 'cyan', + 74 => 'cyan', + 75 => 'cyan', + 76 => 'green', + 77 => 'green', + 78 => 'green', + 79 => 'green', + 80 => 'cyan', + 81 => 'cyan', + 82 => 'green', + 83 => 'green', + 84 => 'green', + 85 => 'green', + 86 => 'cyan', + 87 => 'cyan', + 88 => 'red', + 89 => 'magenta', + 90 => 'magenta', + 91 => 'magenta', + 92 => 'blue', + 93 => 'blue', + 94 => 'yellow', + 95 => 'red', + 96 => 'magenta', + 97 => 'magenta', + 98 => 'blue', + 99 => 'blue', + 100 => 'yellow', + 101 => 'yellow', + 102 => 'white', + 103 => 'blue', + 104 => 'blue', + 105 => 'blue', + 106 => 'green', + 107 => 'green', + 108 => 'green', + 109 => 'cyan', + 110 => 'cyan', + 111 => 'cyan', + 112 => 'green', + 113 => 'green', + 114 => 'green', + 115 => 'green', + 116 => 'cyan', + 117 => 'cyan', + 118 => 'green', + 119 => 'green', + 120 => 'green', + 121 => 'green', + 122 => 'green', + 123 => 'cyan', + 124 => 'red', + 125 => 'magenta', + 126 => 'magenta', + 127 => 'magenta', + 128 => 'magenta', + 129 => 'magenta', + 130 => 'red', + 131 => 'red', + 132 => 'magenta', + 133 => 'magenta', + 134 => 'magenta', + 135 => 'magenta', + 136 => 'yellow', + 137 => 'red', + 138 => 'red', + 139 => 'magenta', + 140 => 'magenta', + 141 => 'magenta', + 142 => 'yellow', + 143 => 'yellow', + 144 => 'yellow', + 145 => 'white', + 146 => 'white', + 147 => 'white', + 148 => 'yellow', + 149 => 'green', + 150 => 'green', + 151 => 'green', + 152 => 'cyan', + 153 => 'white', + 154 => 'green', + 155 => 'green', + 156 => 'green', + 157 => 'green', + 158 => 'green', + 159 => 'cyan', + 160 => 'red', + 161 => 'magenta', + 162 => 'magenta', + 163 => 'magenta', + 164 => 'magenta', + 165 => 'magenta', + 166 => 'red', + 167 => 'red', + 168 => 'magenta', + 169 => 'magenta', + 170 => 'magenta', + 171 => 'magenta', + 172 => 'red', + 173 => 'red', + 174 => 'red', + 175 => 'magenta', + 176 => 'magenta', + 177 => 'magenta', + 178 => 'yellow', + 179 => 'yellow', + 180 => 'white', + 181 => 'white', + 182 => 'magenta', + 183 => 'magenta', + 184 => 'yellow', + 185 => 'yellow', + 186 => 'yellow', + 187 => 'yellow', + 188 => 'white', + 189 => 'white', + 190 => 'yellow', + 191 => 'yellow', + 192 => 'green', + 193 => 'green', + 194 => 'green', + 195 => 'cyan', + 196 => 'red', + 197 => 'red', + 198 => 'magenta', + 199 => 'magenta', + 200 => 'magenta', + 201 => 'magenta', + 202 => 'red', + 203 => 'red', + 204 => 'magenta', + 205 => 'magenta', + 206 => 'magenta', + 207 => 'magenta', + 208 => 'red', + 209 => 'red', + 210 => 'red', + 211 => 'magenta', + 212 => 'magenta', + 213 => 'magenta', + 214 => 'red', + 215 => 'white', + 216 => 'red', + 217 => 'red', + 218 => 'magenta', + 219 => 'magenta', + 220 => 'yellow', + 221 => 'yellow', + 222 => 'yellow', + 223 => 'white', + 224 => 'white', + 225 => 'magenta', + 226 => 'yellow', + 227 => 'yellow', + 228 => 'yellow', + 229 => 'yellow', + 230 => 'yellow', + 231 => 'white', + 232 => 'black', + 233 => 'black', + 234 => 'black', + 235 => 'black', + 236 => 'black', + 237 => 'black', + 238 => 'black', + 239 => 'black', + 240 => 'black', + 241 => 'black', + 242 => 'black', + 243 => 'black', + 244 => 'white', + 245 => 'white', + 246 => 'white', + 247 => 'white', + 248 => 'white', + 249 => 'white', + 250 => 'white', + 251 => 'white', + 252 => 'white', + 253 => 'white', + 254 => 'white', + 255 => 'white', + ]; + + public static function getDefaultColourNames() : array + { + return self::$defaultColoursNames; + } + + /** + * Simple function to transform a 8-bit (256 colours) colour code + * to one of the default 8 colors available in the terminal + */ + public static function map256To8(int $colourCode) : string + { + if (!isset(self::$coloursMap[$colourCode])) { + throw new \InvalidArgumentException('Invalid colour code'); + } + + return self::$coloursMap[$colourCode]; + } + + /** + * Check if $colour exists + * If it's a 256-colours code and $terminal doesn't support it, returns a fallback value + */ + public static function validateColour(Terminal $terminal, string $colour, string $fallback = null) : string + { + if (!ctype_digit($colour)) { + return self::validateColourName($colour); + } + + Assertion::between($colour, 0, 255, 'Invalid colour code'); + + if ($terminal->getColourSupport() >= 256) { + return $colour; + } + + if ($fallback !== null) { + return self::validateColourName($fallback); + } + + return static::map256To8((int) $colour); + } + + private static function validateColourName(string $colourName) : string + { + Assertion::inArray($colourName, static::getDefaultColourNames()); + return $colourName; + } +} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Util/StringUtil.php b/src/ncc/ThirdParty/php-school/cli-menu/Util/StringUtil.php new file mode 100644 index 0000000..8cbba5a --- /dev/null +++ b/src/ncc/ThirdParty/php-school/cli-menu/Util/StringUtil.php @@ -0,0 +1,52 @@ + + */ +class StringUtil +{ + /** + * Minimal multi-byte wordwrap implementation + * which also takes break length into consideration + */ + public static function wordwrap(string $string, int $width, string $break = "\n") : string + { + return implode( + $break, + array_map(function (string $line) use ($width, $break) { + $line = rtrim($line); + if (mb_strlen($line) <= $width) { + return $line; + } + + $words = explode(' ', $line); + $line = ''; + $actual = ''; + foreach ($words as $word) { + if (mb_strlen($actual . $word) <= $width) { + $actual .= $word . ' '; + } else { + if ($actual !== '') { + $line .= rtrim($actual) . $break; + } + $actual = $word . ' '; + } + } + return $line . trim($actual); + }, explode("\n", $string)) + ); + } + + public static function stripAnsiEscapeSequence(string $str) : string + { + return (string) preg_replace('/\x1b[^m]*m/', '', $str); + } + + public static function length(string $str, bool $ignoreAnsiEscapeSequence = true) : int + { + return mb_strlen($ignoreAnsiEscapeSequence ? self::stripAnsiEscapeSequence($str) : $str); + } +} diff --git a/src/ncc/autoload.php b/src/ncc/autoload.php index 488407e..95641bd 100644 --- a/src/ncc/autoload.php +++ b/src/ncc/autoload.php @@ -9,6 +9,7 @@ spl_autoload_register( $classes = array( 'ncc\\abstracts\\exceptioncodes' => '/Abstracts/ExceptionCodes.php', 'ncc\\abstracts\\regexpatterns' => '/Abstracts/RegexPatterns.php', + 'ncc\\exceptions\\filenotfoundexception' => '/Exceptions/FileNotFoundException.php', 'ncc\\exceptions\\invalidprojectconfigurationexception' => '/Exceptions/InvalidProjectConfigurationException.php', 'ncc\\ncc' => '/ncc.php', 'ncc\\objects\\projectconfiguration' => '/Objects/ProjectConfiguration.php', @@ -20,6 +21,49 @@ spl_autoload_register( 'ncc\\objects\\projectconfiguration\\project' => '/Objects/ProjectConfiguration/Project.php', 'ncc\\utilities\\functions' => '/Utilities/Functions.php', 'ncc\\utilities\\validate' => '/Utilities/Validate.php', + 'phpschool\\climenu\\action\\exitaction' => '/ThirdParty/php-school/cli-menu/Action/ExitAction.php', + 'phpschool\\climenu\\action\\gobackaction' => '/ThirdParty/php-school/cli-menu/Action/GoBackAction.php', + 'phpschool\\climenu\\builder\\climenubuilder' => '/ThirdParty/php-school/cli-menu/Builder/CliMenuBuilder.php', + 'phpschool\\climenu\\builder\\splititembuilder' => '/ThirdParty/php-school/cli-menu/Builder/SplitItemBuilder.php', + 'phpschool\\climenu\\climenu' => '/ThirdParty/php-school/cli-menu/CliMenu.php', + 'phpschool\\climenu\\dialogue\\cancellableconfirm' => '/ThirdParty/php-school/cli-menu/Dialogue/CancellableConfirm.php', + 'phpschool\\climenu\\dialogue\\confirm' => '/ThirdParty/php-school/cli-menu/Dialogue/Confirm.php', + 'phpschool\\climenu\\dialogue\\dialogue' => '/ThirdParty/php-school/cli-menu/Dialogue/Dialogue.php', + 'phpschool\\climenu\\dialogue\\flash' => '/ThirdParty/php-school/cli-menu/Dialogue/Flash.php', + 'phpschool\\climenu\\exception\\cannotshrinkmenuexception' => '/ThirdParty/php-school/cli-menu/Exception/CannotShrinkMenuException.php', + 'phpschool\\climenu\\exception\\invalidshortcutexception' => '/ThirdParty/php-school/cli-menu/Exception/InvalidShortcutException.php', + 'phpschool\\climenu\\exception\\invalidterminalexception' => '/ThirdParty/php-school/cli-menu/Exception/InvalidTerminalException.php', + 'phpschool\\climenu\\exception\\menunotopenexception' => '/ThirdParty/php-school/cli-menu/Exception/MenuNotOpenException.php', + 'phpschool\\climenu\\frame' => '/ThirdParty/php-school/cli-menu/Frame.php', + 'phpschool\\climenu\\input\\input' => '/ThirdParty/php-school/cli-menu/Input/Input.php', + 'phpschool\\climenu\\input\\inputio' => '/ThirdParty/php-school/cli-menu/Input/InputIO.php', + 'phpschool\\climenu\\input\\inputresult' => '/ThirdParty/php-school/cli-menu/Input/InputResult.php', + 'phpschool\\climenu\\input\\number' => '/ThirdParty/php-school/cli-menu/Input/Number.php', + 'phpschool\\climenu\\input\\password' => '/ThirdParty/php-school/cli-menu/Input/Password.php', + 'phpschool\\climenu\\input\\text' => '/ThirdParty/php-school/cli-menu/Input/Text.php', + 'phpschool\\climenu\\menuitem\\asciiartitem' => '/ThirdParty/php-school/cli-menu/MenuItem/AsciiArtItem.php', + 'phpschool\\climenu\\menuitem\\checkboxitem' => '/ThirdParty/php-school/cli-menu/MenuItem/CheckboxItem.php', + 'phpschool\\climenu\\menuitem\\linebreakitem' => '/ThirdParty/php-school/cli-menu/MenuItem/LineBreakItem.php', + 'phpschool\\climenu\\menuitem\\menuiteminterface' => '/ThirdParty/php-school/cli-menu/MenuItem/MenuItemInterface.php', + 'phpschool\\climenu\\menuitem\\menumenuitem' => '/ThirdParty/php-school/cli-menu/MenuItem/MenuMenuItem.php', + 'phpschool\\climenu\\menuitem\\propagatesstyles' => '/ThirdParty/php-school/cli-menu/MenuItem/PropagatesStyles.php', + 'phpschool\\climenu\\menuitem\\radioitem' => '/ThirdParty/php-school/cli-menu/MenuItem/RadioItem.php', + 'phpschool\\climenu\\menuitem\\selectableitem' => '/ThirdParty/php-school/cli-menu/MenuItem/SelectableItem.php', + 'phpschool\\climenu\\menuitem\\selectableitemrenderer' => '/ThirdParty/php-school/cli-menu/MenuItem/SelectableItemRenderer.php', + 'phpschool\\climenu\\menuitem\\splititem' => '/ThirdParty/php-school/cli-menu/MenuItem/SplitItem.php', + 'phpschool\\climenu\\menuitem\\staticitem' => '/ThirdParty/php-school/cli-menu/MenuItem/StaticItem.php', + 'phpschool\\climenu\\menustyle' => '/ThirdParty/php-school/cli-menu/MenuStyle.php', + 'phpschool\\climenu\\style\\checkboxstyle' => '/ThirdParty/php-school/cli-menu/Style/CheckboxStyle.php', + 'phpschool\\climenu\\style\\defaultstyle' => '/ThirdParty/php-school/cli-menu/Style/DefaultStyle.php', + 'phpschool\\climenu\\style\\exception\\invalidstyle' => '/ThirdParty/php-school/cli-menu/Style/Exception/InvalidStyle.php', + 'phpschool\\climenu\\style\\itemstyle' => '/ThirdParty/php-school/cli-menu/Style/ItemStyle.php', + 'phpschool\\climenu\\style\\locator' => '/ThirdParty/php-school/cli-menu/Style/Locator.php', + 'phpschool\\climenu\\style\\radiostyle' => '/ThirdParty/php-school/cli-menu/Style/RadioStyle.php', + 'phpschool\\climenu\\style\\selectablestyle' => '/ThirdParty/php-school/cli-menu/Style/SelectableStyle.php', + 'phpschool\\climenu\\terminal\\terminalfactory' => '/ThirdParty/php-school/cli-menu/Terminal/TerminalFactory.php', + 'phpschool\\climenu\\util\\collection' => '/ThirdParty/php-school/cli-menu/Util/Collection.php', + 'phpschool\\climenu\\util\\colourutil' => '/ThirdParty/php-school/cli-menu/Util/ColourUtil.php', + 'phpschool\\climenu\\util\\stringutil' => '/ThirdParty/php-school/cli-menu/Util/StringUtil.php', 'symfony\\component\\nccprocess\\exception\\exceptioninterface' => '/ThirdParty/Symfony/Process/Exception/ExceptionInterface.php', 'symfony\\component\\nccprocess\\exception\\invalidargumentexception' => '/ThirdParty/Symfony/Process/Exception/InvalidArgumentException.php', 'symfony\\component\\nccprocess\\exception\\logicexception' => '/ThirdParty/Symfony/Process/Exception/LogicException.php', diff --git a/tests/autoload.php b/tests/autoload.php index b3d9bbc..1609468 100644 --- a/tests/autoload.php +++ b/tests/autoload.php @@ -1 +1,8 @@