================================================================================
INTOUCH FRAMEWORK - DOCUMENTACIÓN COMPLETA
PARA REGISTRO EN DEPARTAMENTO DE DERECHOS INTELECTUALES
================================================================================
Autor: Claudio Alfonso González Almeyda
Año de Creación: 2018
Año Actual: 2025
Framework: InTouch Framework
Esta documentación contiene el código fuente completo del InTouch Framework
para su registro en el Departamento de Derechos Intelectuales de Chile.
Fecha de Generación: 2025-11-03 20:16:06
================================================================================
ESTRUCTURA DEL PROYECTO
================================================================================
Total de archivos: 464
Tamaño total: 1.52 MB
LISTA DE ARCHIVOS:
--------------------------------------------------------------------------------
1. generate_documentation.php 4.78 KB
2. src/Annotation/AnnotationHelper.php 12.32 KB
3. src/Annotation/AttributeContainer.php 1.87 KB
4. src/Annotation/Attributes/CacheMulti.php 380 bytes
5. src/Annotation/Attributes/CacheSingle.php 381 bytes
6. src/Annotation/Attributes/CheckSession.php 356 bytes
7. src/Annotation/Attributes/ConfigDetails.php 411 bytes
8. src/Annotation/Attributes/Entity.php 563 bytes
9. src/Annotation/Attributes/EntityField.php 865 bytes
10. src/Annotation/Attributes/Key.php 347 bytes
11. src/Annotation/Attributes/PreventCache.php 382 bytes
12. src/Annotation/Attributes/ReturnActionResult.php 389 bytes
13. src/Annotation/Attributes/ReturnActionViewResult.php 393 bytes
14. src/Annotation/Attributes/ReturnExcelResult.php 388 bytes
15. src/Annotation/Attributes/ReturnJsonPlainResult.php 392 bytes
16. src/Annotation/Attributes/ReturnJsonResult.php 387 bytes
17. src/Annotation/Attributes/ReturnJsonResultMovil.php 392 bytes
18. src/Annotation/Attributes/ReturnPdfInlineResult.php 392 bytes
19. src/Annotation/Attributes/ReturnRedirectResult.php 391 bytes
20. src/Annotation/Attributes/ReturnViewResult.php 387 bytes
21. src/Annotation/Attributes/Route.php 780 bytes
22. src/Annotation/Attributes/Template.php 469 bytes
23. src/Annotation/Attributes/ViewDisplay.php 580 bytes
24. src/Annotation/Attributes/ViewDisplayKey.php 360 bytes
25. src/Annotation/Attributes/Widget.php 521 bytes
26. src/Annotation/ClassAttribute.php 377 bytes
27. src/Annotation/ContainerTypeEnum.php 397 bytes
28. src/Annotation/MethodAttribute.php 437 bytes
29. src/Annotation/MethodParameter.php 527 bytes
30. src/Annotation/PropertyAttribute.php 383 bytes
31. src/Assets/Entities/ImageResource.php 1.12 KB
32. src/Assets/Entities/PdfResource.php 361 bytes
33. src/Assets/IAssetManager.php 447 bytes
34. src/Assets/IAssetManagerFactory.php 534 bytes
35. src/Assets/Managers/CloudFrontAssetManager.php 2.32 KB
36. src/Assets/Managers/LocalAssetManager.php 1.29 KB
37. src/Assets/Managers/S3AssetManager.php 1.54 KB
38. src/Assets/Requests/CloudFrontImageRequest.php 987 bytes
39. src/Assets/Resource.php 1.18 KB
40. src/BLL/DataTransferObjects/RangoDto.php 368 bytes
41. src/BLL/Filters/CustomExcelSettingsFilterDto.php 553 bytes
42. src/BLL/Filters/DataTableSettingsFilterDto.php 1.54 KB
43. src/BLL/Service/GenericSvc.php 7.03 KB
44. src/BLL/WebService/HttpHelper.php 5.23 KB
45. src/BLL/WebService/HttpMethodEnum.php 400 bytes
46. src/Bin/environment.php 270 bytes
47. src/Bin/generator.php 1.27 KB
48. src/Bin/mantenedor.php 1.27 KB
49. src/Cache/Page.php 25.80 KB
50. src/Cache/PageDefinition.php 1.49 KB
51. src/Cache/PageResults.php 475 bytes
52. src/Cache/RedisSvc.php 1.37 KB
53. src/Collection/AttachDefinition.php 537 bytes
54. src/Collection/CollectionDefinition.php 543 bytes
55. src/Collection/Collections.php 15.39 KB
56. src/Collection/Condition.php 698 bytes
57. src/Collection/ConditionBuilder.php 4.72 KB
58. src/Collection/GenericCollection.php 41.63 KB
59. src/Collection/GenericDefinition.php 2.43 KB
60. src/Collection/GenericValidator.php 3.51 KB
61. src/Collection/MergeDefinition.php 514 bytes
62. src/Configuration/BaseConfig.php 1.97 KB
63. src/Configuration/BundleConfig.php 1.65 KB
64. src/Configuration/ConnectionConfig.php 1.04 KB
65. src/Configuration/MensajeConfig.php 937 bytes
66. src/Configuration/MenuConfig.php 10.08 KB
67. src/Configuration/RedisConfig.php 908 bytes
68. src/Configuration/RestrictionConfig.php 2.13 KB
69. src/Configuration/SystemConfig.php 2.40 KB
70. src/Controllers/ActionResult.php 865 bytes
71. src/Controllers/ActionViewResult.php 868 bytes
72. src/Controllers/BaseController.php 30.21 KB
73. src/Controllers/Chart/LineChartSerie.php 495 bytes
74. src/Controllers/Chart/PieChartSerie.php 454 bytes
75. src/Controllers/Chart/SeriesColorEnum.php 688 bytes
76. src/Controllers/ChartHelper.php 5.54 KB
77. src/Controllers/ControllerDefinition.php 691 bytes
78. src/Controllers/Display.php 7.78 KB
79. src/Controllers/ErrorJsonMovilResult.php 507 bytes
80. src/Controllers/ErrorJsonResult.php 688 bytes
81. src/Controllers/ErrorResult.php 944 bytes
82. src/Controllers/ErrorViewResult.php 1006 bytes
83. src/Controllers/ExcelResult.php 857 bytes
84. src/Controllers/InternalControllers/DefaultAssetManager.php 1023 bytes
85. src/Controllers/InternalControllers/DefaultAssetManagerFactory.php 927 bytes
86. src/Controllers/InternalControllers/PageController.php 1.19 KB
87. src/Controllers/JsonPlainResult.php 386 bytes
88. src/Controllers/JsonResult.php 677 bytes
89. src/Controllers/JsonResultMovil.php 479 bytes
90. src/Controllers/PdfInlineResult.php 860 bytes
91. src/Controllers/RedirectResult.php 864 bytes
92. src/Controllers/Result.php 575 bytes
93. src/Controllers/ResultPrevio.php 475 bytes
94. src/Controllers/ViewResult.php 856 bytes
95. src/Core/Audit.php 3.35 KB
96. src/Core/Cacheable.php 1.33 KB
97. src/Core/CacheableSingleton.php 2.25 KB
98. src/Core/Dynamic.php 344 bytes
99. src/Core/ErrorTypeEnum.php 382 bytes
100. src/Core/FileHelper.php 1.04 KB
101. src/Core/Log.php 6.83 KB
102. src/Core/MemoryInfo.php 1.50 KB
103. src/Core/Rut.php 1.14 KB
104. src/Core/SingleSignOn/OpenId.php 4.15 KB
105. src/Core/System.php 2.99 KB
106. src/Dao/AuditField.php 859 bytes
107. src/Dao/AuditInfo.php 3.90 KB
108. src/Dao/BasicDao.php 31.77 KB
109. src/Dao/BindVariable.php 2.32 KB
110. src/Dao/ConnectionTypeEnum.php 411 bytes
111. src/Dao/DataConfig.php 2.17 KB
112. src/Dao/DefinitionTypeEnum.php 453 bytes
113. src/Dao/Entity/Annotation.php 343 bytes
114. src/Dao/Entity/DocComment.php 2.42 KB
115. src/Dao/Entity/EntityDefinition.php 9.28 KB
116. src/Dao/Entity/IAuditable.php 389 bytes
117. src/Dao/Entity/PropertyDefinition.php 3.33 KB
118. src/Dao/ExecuteDao.php 6.53 KB
119. src/Dao/Format.php 480 bytes
120. src/Dao/FormatTypeEnum.php 451 bytes
121. src/Dao/GenericDao.php 18.28 KB
122. src/Dao/OperatorEnum.php 551 bytes
123. src/Dao/Queryable.php 23.83 KB
124. src/Dates/Date.php 20.25 KB
125. src/Dates/Interval.php 2.48 KB
126. src/Document/GenericDocument.php 6.98 KB
127. src/Document/GenericDocumentDefinition.php 548 bytes
128. src/Document/GenericFileExtensionEnum.php 425 bytes
129. src/Environment/Globals.php 1.14 KB
130. src/Environment/Headers.php 1.33 KB
131. src/Environment/Ini.php 1.28 KB
132. src/Environment/IniEnum.php 553 bytes
133. src/Environment/Request.php 1.67 KB
134. src/Environment/Server.php 1.07 KB
135. src/Environment/Session.php 1.14 KB
136. src/Exceptions/BaseException.php 594 bytes
137. src/Exceptions/BusinessException.php 2.38 KB
138. src/Exceptions/ExceptionCodesEnum.php 866 bytes
139. src/Exceptions/ExceptionResult.php 623 bytes
140. src/Exceptions/ExceptionTypeEnum.php 485 bytes
141. src/Generator/Config.php 1.46 KB
142. src/Generator/Engine.php 80.64 KB
143. src/Generator/Templates/Dao.php 552 bytes
144. src/Generator/Templates/DaoT.php 235 bytes
145. src/Generator/Templates/Dto.php 441 bytes
146. src/Generator/Templates/DtoT.php 461 bytes
147. src/Generator/Templates/Ent.php 837 bytes
148. src/Generator/Templates/EntT.php 288 bytes
149. src/Generator/Templates/Mantenedores/ApiController.php 6.59 KB
150. src/Generator/Templates/Mantenedores/ApiControllerT.php 261 bytes
151. src/Generator/Templates/Mantenedores/BusinessObject.php 10.19 KB
152. src/Generator/Templates/Mantenedores/BusinessObjectT.php 1.82 KB
153. src/Generator/Templates/Mantenedores/ViewController.php 1.35 KB
154. src/Generator/Templates/Mantenedores/ViewControllerT.php 257 bytes
155. src/Generator/Templates/Mantenedores/popupView.php 9.67 KB
156. src/Generator/Templates/Mantenedores/verGridAsPopUpView.php 5.78 KB
157. src/Generator/Templates/Mantenedores/verGridT.php 7.90 KB
158. src/Generator/Templates/Mantenedores/verGridView.php 4.93 KB
159. src/Generator/Templates/Mantenedores/verView.php 7.77 KB
160. src/Generator/Templates/Svc.php 842 bytes
161. src/Generator/Templates/SvcT.php 266 bytes
162. src/Generator/TemplatesOld/Dao.php 481 bytes
163. src/Generator/TemplatesOld/DaoT.php 208 bytes
164. src/Generator/TemplatesOld/Dto.php 300 bytes
165. src/Generator/TemplatesOld/DtoT.php 438 bytes
166. src/Generator/TemplatesOld/Ent.php 425 bytes
167. src/Generator/TemplatesOld/EntT.php 261 bytes
168. src/Generator/TemplatesOld/Mantenedores/ApiController.php 3.40 KB
169. src/Generator/TemplatesOld/Mantenedores/ApiControllerT.php 234 bytes
170. src/Generator/TemplatesOld/Mantenedores/BusinessObject.php 4.49 KB
171. src/Generator/TemplatesOld/Mantenedores/BusinessObjectT.php 230 bytes
172. src/Generator/TemplatesOld/Mantenedores/Prueba.php 595 bytes
173. src/Generator/TemplatesOld/Mantenedores/ViewController.php 1.22 KB
174. src/Generator/TemplatesOld/Mantenedores/ViewControllerT.php 230 bytes
175. src/Generator/TemplatesOld/Mantenedores/popupView.php 3.21 KB
176. src/Generator/TemplatesOld/Mantenedores/verGridAsPopUpView.php 2.74 KB
177. src/Generator/TemplatesOld/Mantenedores/verGridT.php 6.04 KB
178. src/Generator/TemplatesOld/Mantenedores/verGridView.php 1.81 KB
179. src/Generator/TemplatesOld/Mantenedores/verView.php 3.73 KB
180. src/Generator/TemplatesOld/Svc.php 707 bytes
181. src/Generator/TemplatesOld/SvcT.php 239 bytes
182. src/IdeHelpers/_ide_helper_redis.php 5.10 KB
183. src/Init/func.php 16.07 KB
184. src/Loaders.php 5.39 KB
185. src/MailHelper/Attachment.php 479 bytes
186. src/MailHelper/ComposeReplacement.php 586 bytes
187. src/MailHelper/DispositionEnum.php 383 bytes
188. src/MailHelper/Mail.php 6.51 KB
189. src/MailHelper/MailConfig.php 475 bytes
190. src/MailHelper/MailUtil.php 805 bytes
191. src/MailHelper/Message.php 496 bytes
192. src/MailHelper/Recipient.php 463 bytes
193. src/MailHelper/RecipientTypeEnum.php 511 bytes
194. src/MailHelper/ResultMultipleSend.php 560 bytes
195. src/Mapper/Map.php 5.34 KB
196. src/Mapper/Mapper.php 21.20 KB
197. src/Mapping/BaseMapper.php 697 bytes
198. src/Mapping/Reflect.php 654 bytes
199. src/Math/Modulo.php 1012 bytes
200. src/Mensajes/Mensaje.php 7.58 KB
201. src/Mensajes/MensajeDto.php 356 bytes
202. src/OfficeHelper/.claude/settings.local.json 99 bytes
203. src/OfficeHelper/BigCsvSql.php 11.23 KB
204. src/OfficeHelper/BigExcel copy.php 35.26 KB
205. src/OfficeHelper/BigExcel.php 65.56 KB
206. src/OfficeHelper/BigExcelDefinition.php 549 bytes
207. src/OfficeHelper/BigExcelSheet.php 721 bytes
208. src/OfficeHelper/BigExcelSql.php 39.05 KB
209. src/OfficeHelper/CeldaExcel.php 720 bytes
210. src/OfficeHelper/Excel.php 22.93 KB
211. src/OfficeHelper/ExcelTemplate/[Content_Types].xml 1.01 KB
212. src/OfficeHelper/ExcelTemplate/docProps/app.xml 988 bytes
213. src/OfficeHelper/ExcelTemplate/docProps/core.xml 651 bytes
214. src/OfficeHelper/ExcelTemplate/xl/styles.xml 1.89 KB
215. src/OfficeHelper/ExcelTemplate/xl/theme/theme1.xml 11.59 KB
216. src/OfficeHelper/ExcelTemplate/xl/workbook.xml 942 bytes
217. src/OfficeHelper/ExcelTemplate/xl/worksheets/sheet_template.xml 580 bytes
218. src/OfficeHelper/ExcelUnzipInfo.php 585 bytes
219. src/OfficeHelper/RowReadFilter.php 795 bytes
220. src/OfficeHelper/SheetDimensions.php 304 bytes
221. src/ProjectionEngine/DefaultProjectionBuilder.php 15.26 KB
222. src/ProjectionEngine/IProjectionBuilder.php 603 bytes
223. src/ProjectionEngine/IProjectionCalculator.php 449 bytes
224. src/ProjectionEngine/IProjectionResultWriter.php 464 bytes
225. src/ProjectionEngine/Intervalo.php 398 bytes
226. src/ProjectionEngine/IntervaloCollection.php 481 bytes
227. src/ProjectionEngine/Projection.php 6.01 KB
228. src/ProjectionEngine/ProjectionValidator.php 1.54 KB
229. src/ProjectionEngine/Projector.php 18.51 KB
230. src/ProjectionEngine/WorkShift.php 10.18 KB
231. src/ProjectionEngine/WorkShiftCompleted.php 1.24 KB
232. src/ProjectionEngine/WorkShiftDatePartEnum.php 401 bytes
233. src/ProjectionEngine/WorkShiftSchedule.php 4.08 KB
234. src/ReportEngine/Report.php 4.71 KB
235. src/ReportEngine/ReportDataset.php 716 bytes
236. src/ReportEngine/ReportDefinition.php 1.98 KB
237. src/ReportEngine/ReportFilter.php 739 bytes
238. src/ReportEngine/ReportOutputDefinition.php 766 bytes
239. src/ReportEngine/ReportOutputEnum.php 403 bytes
240. src/Route/BaseDispatcher.php 25.01 KB
241. src/Route/ControllerContainer.php 1.78 KB
242. src/Route/IDispatchResponse.php 1.67 KB
243. src/Route/RouteHelper.php 13.71 KB
244. src/Route/Uri.php 10.52 KB
245. src/Security/Encoder.php 3.98 KB
246. src/String/Concat.php 1.31 KB
247. src/Stubs/Intouch/Dao/BasicDao.zep.php 502 bytes
248. src/Stubs/Intouch/Dao/ExecuteDao.zep.php 389 bytes
249. src/Stubs/Intouch/Dao/GenericDao.zep.php 456 bytes
250. src/Styles/StyleObject.php 2.74 KB
251. src/Styles/ThemeConfig.php 4.58 KB
252. src/Styles/TipoLoginEnum.php 416 bytes
253. src/SystemViews/localizationView.php 16.95 KB
254. src/Utils.php 4.10 KB
255. src/View/Display.php 150.54 KB
256. src/View/DisplayDefinitions/Button.php 1.68 KB
257. src/View/DisplayDefinitions/ButtonBadge.php 675 bytes
258. src/View/DisplayDefinitions/DisplayFunctionModeEnum.php 396 bytes
259. src/View/DisplayDefinitions/FormButton.php 1.25 KB
260. src/View/DisplayDefinitions/FormRowField.php 1.36 KB
261. src/View/DisplayDefinitions/FormRowFieldCheck.php 1.80 KB
262. src/View/DisplayDefinitions/FormRowFieldContent.php 743 bytes
263. src/View/DisplayDefinitions/FormRowFieldDate.php 1.46 KB
264. src/View/DisplayDefinitions/FormRowFieldEmpty.php 493 bytes
265. src/View/DisplayDefinitions/FormRowFieldFile.php 1.23 KB
266. src/View/DisplayDefinitions/FormRowFieldHidden.php 706 bytes
267. src/View/DisplayDefinitions/FormRowFieldLabel.php 780 bytes
268. src/View/DisplayDefinitions/FormRowFieldSelect.php 1.12 KB
269. src/View/DisplayDefinitions/FormRowFieldSelectDefinition.php 1.14 KB
270. src/View/DisplayDefinitions/FormRowFieldSubTitle.php 598 bytes
271. src/View/DisplayDefinitions/FormRowFieldText.php 1.93 KB
272. src/View/DisplayDefinitions/FormRowFieldTypeEnum.php 1.04 KB
273. src/View/DisplayDefinitions/FormRowGroup.php 988 bytes
274. src/View/DisplayDefinitions/FormRowSection.php 400 bytes
275. src/View/DisplayDefinitions/HrefSpec.php 425 bytes
276. src/View/DisplayDefinitions/JSTable/JSTableBodyTemplate.php 414 bytes
277. src/View/DisplayDefinitions/JSTable/JSTableCell.php 1.42 KB
278. src/View/DisplayDefinitions/JSTable/JSTableCellDefinitions.php 784 bytes
279. src/View/DisplayDefinitions/JSTableButton.php 2.09 KB
280. src/View/DisplayDefinitions/LabelSpec.php 432 bytes
281. src/View/DisplayDefinitions/Tab.php 1.13 KB
282. src/View/DisplayDefinitions/TableButton.php 2.15 KB
283. src/View/DisplayDefinitions/TableCell.php 865 bytes
284. src/View/DisplayDefinitions/TableDropDownButton.php 1.64 KB
285. src/View/DisplayDefinitions/TableJSCell.php 3.12 KB
286. src/View/DisplayDefinitions/TableJSCellFunctions.php 8.81 KB
287. src/View/DisplayDefinitions/TogglePlacementEnum.php 454 bytes
288. src/View/DisplayDefinitions/ValidadoresEnum.php 440 bytes
289. src/View/DisplayDefinitions/ValidationRuleEnum.php 471 bytes
290. src/View/DisplayEnumerations/DateRangeIntervalsEnum.php 691 bytes
291. src/View/DisplayEventActions/Action.php 1.06 KB
292. src/View/DisplayEventActions/CallFunctionAction.php 1.14 KB
293. src/View/DisplayEventActions/ChangeVisibilityAction.php 2.34 KB
294. src/View/DisplayEventActions/RefreshListAction.php 3.22 KB
295. src/View/DisplayEventActions/VisibilityActionEnum.php 470 bytes
296. src/View/DisplayEvents/ButtonOnClickEvent.php 751 bytes
297. src/View/DisplayEvents/Event.php 1.56 KB
298. src/View/DisplayEvents/FormButtonOnClickEvent.php 686 bytes
299. src/View/DisplayEvents/FormEvent.php 3.31 KB
300. src/View/DisplayEvents/FormOnBlurEvent.php 670 bytes
301. src/View/DisplayEvents/FormOnChangeEvent.php 837 bytes
302. src/View/DisplayEvents/FormOnClickEvent.php 750 bytes
303. src/View/DisplayEvents/FormOnKeyPressEvent.php 1.73 KB
304. src/View/DisplayEvents/FormOnKeyUpEvent.php 1.17 KB
305. src/View/DisplayEvents/JsEventEnum.php 570 bytes
306. src/View/DisplayEvents/JsRegExpEnum.php 435 bytes
307. src/View/DisplayEvents/SexyPageButtonOnClickEvent.php 1.21 KB
308. src/View/DisplayEvents/SexyPageButtonOnRefreshEvent.php 2.85 KB
309. src/View/DisplayEvents/TableButtonOnClickEvent.php 993 bytes
310. src/View/DisplayEvents/TableEvent.php 2.72 KB
311. src/View/DisplayValidations/Validation.php 398 bytes
312. src/Widget/Action.php 1.48 KB
313. src/Widget/ActionButton.php 4.00 KB
314. src/Widget/ActionButtonDropDown.php 3.81 KB
315. src/Widget/ActionButtonDropDownChild.php 3.41 KB
316. src/Widget/ActionMenu.php 2.36 KB
317. src/Widget/ActionMenuItem.php 1.48 KB
318. src/Widget/ActionMenuMiniSeparator.php 894 bytes
319. src/Widget/ActionMenuSeparator.php 886 bytes
320. src/Widget/ActionMenuTitle.php 963 bytes
321. src/Widget/ActionMenuTitleSubtitle.php 2.55 KB
322. src/Widget/ActionMenuTree.php 1.76 KB
323. src/Widget/Am5Chart.php 1.69 KB
324. src/Widget/AmChartGeneric.php 3.38 KB
325. src/Widget/AmChartGraph.php 31.28 KB
326. src/Widget/AmchartPie.php 5.39 KB
327. src/Widget/Card.php 3.58 KB
328. src/Widget/CardAction.php 2.52 KB
329. src/Widget/CardActionIconText.php 3.20 KB
330. src/Widget/CardActionImageText.php 3.59 KB
331. src/Widget/CardIconText.php 2.56 KB
332. src/Widget/Chart.php 1.36 KB
333. src/Widget/Container.php 3.59 KB
334. src/Widget/DateAndTime.php 2.79 KB
335. src/Widget/Definitions/Action/ActionTargetEnum.php 479 bytes
336. src/Widget/Definitions/ActionButton/ButtonStyleEnum.php 623 bytes
337. src/Widget/Definitions/ActionMenu/AnimationTypeEnum.php 2.15 KB
338. src/Widget/Definitions/AmChart/AmChartAddData.php 693 bytes
339. src/Widget/Definitions/AmChart/AmChartBarData.php 3.45 KB
340. src/Widget/Definitions/AmChart/AmChartColorEnum.php 508 bytes
341. src/Widget/Definitions/AmChart/AmChartControls.php 2.10 KB
342. src/Widget/Definitions/AmChart/AmChartGeneric.php 1.11 KB
343. src/Widget/Definitions/AmChart/AmChartGenericToAmData.php 4.14 KB
344. src/Widget/Definitions/AmChart/AmChartLegend.php 3.69 KB
345. src/Widget/Definitions/AmChart/AmChartPieData.php 2.60 KB
346. src/Widget/Definitions/AmChart/AmChartSeries.php 1.16 KB
347. src/Widget/Definitions/AmChart/AmChartTypeEnum.php 1007 bytes
348. src/Widget/Definitions/AmChart5/Axis/Axis.php 629 bytes
349. src/Widget/Definitions/AmChart5/Axis/CategoryAxis.php 1.19 KB
350. src/Widget/Definitions/AmChart5/Axis/RoundedRectangleTitle.php 2.20 KB
351. src/Widget/Definitions/AmChart5/Axis/Title.php 3.29 KB
352. src/Widget/Definitions/AmChart5/Axis/ValueAxis.php 1.83 KB
353. src/Widget/Definitions/AmChart5/Axis/XAxis.php 557 bytes
354. src/Widget/Definitions/AmChart5/Basic.php 2.05 KB
355. src/Widget/Definitions/AmChart5/Chart/Chart.php 1.24 KB
356. src/Widget/Definitions/AmChart5/Chart/ChartOrientationEnum.php 393 bytes
357. src/Widget/Definitions/AmChart5/Chart/ChartXY.php 3.86 KB
358. src/Widget/Definitions/AmChart5/Chart/ChartXY2.php 3.93 KB
359. src/Widget/Definitions/AmChart5/Data/DataCollection.php 1.09 KB
360. src/Widget/Definitions/AmChart5/Data/DataItem.php 1.27 KB
361. src/Widget/Definitions/AmChart5/Data/DataItemDefinition.php 844 bytes
362. src/Widget/Definitions/AmChart5/Enum/AlignEnum.php 428 bytes
363. src/Widget/Definitions/AmChart5/Enum/ColorEnum.php 1.09 KB
364. src/Widget/Definitions/AmChart5/Enum/VerticalAlignEnum.php 431 bytes
365. src/Widget/Definitions/AmChart5/RootElement.php 2.17 KB
366. src/Widget/Definitions/AmChart5/Series/AxisDefinition.php 445 bytes
367. src/Widget/Definitions/AmChart5/Series/Bullet.php 446 bytes
368. src/Widget/Definitions/AmChart5/Series/ColumnSeriesDefinition.php 1.61 KB
369. src/Widget/Definitions/AmChart5/Series/LabelSprite.php 666 bytes
370. src/Widget/Definitions/AmChart5/Series/LineSeriesDefinition.php 1.26 KB
371. src/Widget/Definitions/AmChart5/Series/Series.php 9.27 KB
372. src/Widget/Definitions/AmChart5/Series/SeriesDefinition.php 888 bytes
373. src/Widget/Definitions/AmChart5/Series/SeriesTypeEnum.php 422 bytes
374. src/Widget/Definitions/AmChart5/Series/Sprite.php 462 bytes
375. src/Widget/Definitions/Chart/ChartDefinition.php 426 bytes
376. src/Widget/Definitions/Chart/ChartTypeEnum.php 678 bytes
377. src/Widget/Definitions/Chart/Root.php 450 bytes
378. src/Widget/Definitions/Chart/XYChart/ValueAxis.php 819 bytes
379. src/Widget/Definitions/Chart/XYChart/XYChartDefinition.php 902 bytes
380. src/Widget/Definitions/Container/Edge.php 610 bytes
381. src/Widget/Definitions/Container/Position.php 658 bytes
382. src/Widget/Definitions/Container/PositionEnum.php 401 bytes
383. src/Widget/Definitions/General/Badge.php 547 bytes
384. src/Widget/Definitions/General/UnitEnum.php 515 bytes
385. src/Widget/Definitions/Label/LabelSizeEnum.php 544 bytes
386. src/Widget/Definitions/Label/LabelStyleEnum.php 894 bytes
387. src/Widget/Definitions/Photo/PhotoDefinition.php 725 bytes
388. src/Widget/Definitions/PopUpModal/ColorLineStyleEnum.php 579 bytes
389. src/Widget/Definitions/Table/ButtonColumnDefinition.php 832 bytes
390. src/Widget/Definitions/Table/ColumnDefinition.php 626 bytes
391. src/Widget/Definitions/Table/ColumnTypeEnum.php 583 bytes
392. src/Widget/Definitions/Table/HeaderColumnDefinition.php 653 bytes
393. src/Widget/Definitions/Table/TableDefinition.php 780 bytes
394. src/Widget/Definitions/TimeLine/TimeLineStyleEnum.php 595 bytes
395. src/Widget/Definitions/ZingChart/ZChart.php 1.88 KB
396. src/Widget/Definitions/ZingChart/ZLabel.php 443 bytes
397. src/Widget/Definitions/ZingChart/ZSerie.php 759 bytes
398. src/Widget/Definitions/ZingChart/ZSeries.php 1.88 KB
399. src/Widget/ExcelInput.php 1.49 KB
400. src/Widget/FaIcon.php 1.25 KB
401. src/Widget/FaIconText.php 1.92 KB
402. src/Widget/FileInput.php 1.48 KB
403. src/Widget/FlexGroup.php 1.92 KB
404. src/Widget/FlexItem.php 1.60 KB
405. src/Widget/Form.php 1.89 KB
406. src/Widget/FormGroup.php 1.82 KB
407. src/Widget/FormGroupColumn.php 2.34 KB
408. src/Widget/FormGroupColumnContent.php 1.88 KB
409. src/Widget/FormGroupColumnEmpty.php 1.60 KB
410. src/Widget/FormGroupColumnLabel.php 4.21 KB
411. src/Widget/FormGroupRow.php 2.04 KB
412. src/Widget/FormGroupSeparator.php 1.23 KB
413. src/Widget/GenericWidget.php 9.34 KB
414. src/Widget/Html.php 560 bytes
415. src/Widget/IDrawable.php 366 bytes
416. src/Widget/Image.php 2.54 KB
417. src/Widget/Input.php 373 bytes
418. src/Widget/InputAddon.php 1.37 KB
419. src/Widget/InputCheck.php 3.20 KB
420. src/Widget/InputColor.php 1.76 KB
421. src/Widget/InputDate.php 2.88 KB
422. src/Widget/InputDateRange.php 2.59 KB
423. src/Widget/InputSelect.php 4.72 KB
424. src/Widget/InputSelectMultiple.php 3.13 KB
425. src/Widget/InputSelectOption.php 938 bytes
426. src/Widget/InputText.php 1.81 KB
427. src/Widget/InputTextArea.php 1.97 KB
428. src/Widget/JSTableContent.php 726 bytes
429. src/Widget/JSTableRow.php 617 bytes
430. src/Widget/JSTableScriptFilter.php 799 bytes
431. src/Widget/Label.php 1.58 KB
432. src/Widget/LeftItem.php 2.96 KB
433. src/Widget/Menu.php 1.59 KB
434. src/Widget/MenuItem.php 1.61 KB
435. src/Widget/Nav.php 1.81 KB
436. src/Widget/PageHeader.php 2.89 KB
437. src/Widget/PageHeaderActionCard.php 5.05 KB
438. src/Widget/Panel.php 3.94 KB
439. src/Widget/Photo.php 2.06 KB
440. src/Widget/PhotoGallery.php 2.17 KB
441. src/Widget/PopUpContent.php 2.86 KB
442. src/Widget/Progress.php 1.84 KB
443. src/Widget/Script.php 844 bytes
444. src/Widget/ScriptDirect.php 945 bytes
445. src/Widget/ScriptDirectSimple.php 1.62 KB
446. src/Widget/SexyTab.php 4.25 KB
447. src/Widget/SexyTabGroup.php 3.63 KB
448. src/Widget/SexyTabPage.php 3.27 KB
449. src/Widget/SimpleList.php 2.15 KB
450. src/Widget/SimpleListItem.php 1.24 KB
451. src/Widget/SimpleScript.php 856 bytes
452. src/Widget/Table.php 2.79 KB
453. src/Widget/TableBody.php 1.06 KB
454. src/Widget/TableColumn.php 1.67 KB
455. src/Widget/TableHeader.php 1010 bytes
456. src/Widget/TableHeaderColumn.php 1.65 KB
457. src/Widget/TableHeaderRow.php 2.35 KB
458. src/Widget/TableRow.php 4.04 KB
459. src/Widget/Text.php 1.34 KB
460. src/Widget/TimeLineContainer.php 3.77 KB
461. src/Widget/TimeLineItem.php 6.29 KB
462. src/Widget/TitleDescription.php 3.62 KB
463. src/Widget/Waiting.php 1.40 KB
464. src/Widget/ZingChart.php 1.57 KB
================================================================================
CONTENIDO DE LOS ARCHIVOS
================================================================================
================================================================================
ARCHIVO #1: generate_documentation.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/generate_documentation.php
Tamaño: 4.78 KB
--------------------------------------------------------------------------------
1 | isFile()) {
38 | $extension = $file->getExtension();
39 | if (in_array($extension, ['php', 'md', 'txt', 'json', 'xml', 'yml', 'yaml'])) {
40 | $relativePath = str_replace($baseDir . '/', '', $file->getPathname());
41 | $files[] = [
42 | 'path' => $file->getPathname(),
43 | 'relative' => $relativePath,
44 | 'size' => $file->getSize()
45 | ];
46 | }
47 | }
48 | }
49 |
50 | usort($files, function($a, $b) {
51 | return strcmp($a['relative'], $b['relative']);
52 | });
53 |
54 | return $files;
55 | }
56 |
57 | function formatBytes($bytes) {
58 | if ($bytes >= 1048576) {
59 | return number_format($bytes / 1048576, 2) . ' MB';
60 | } elseif ($bytes >= 1024) {
61 | return number_format($bytes / 1024, 2) . ' KB';
62 | } else {
63 | return $bytes . ' bytes';
64 | }
65 | }
66 |
67 | echo "Generando documentación para DDI...\n";
68 | echo "Directorio base: $baseDir\n";
69 | echo "Archivo de salida: $outputFile\n\n";
70 |
71 | $files = getAllFiles($baseDir, $baseDir);
72 | $totalFiles = count($files);
73 | $totalSize = array_sum(array_column($files, 'size'));
74 |
75 | echo "Archivos encontrados: $totalFiles\n";
76 | echo "Tamaño total: " . formatBytes($totalSize) . "\n\n";
77 |
78 | $output = sprintf($header, date('Y-m-d H:i:s'));
79 |
80 | $output .= "Total de archivos: $totalFiles\n";
81 | $output .= "Tamaño total: " . formatBytes($totalSize) . "\n\n";
82 |
83 | $output .= "LISTA DE ARCHIVOS:\n";
84 | $output .= str_repeat("-", 80) . "\n";
85 |
86 | foreach ($files as $index => $file) {
87 | $num = $index + 1;
88 | $output .= sprintf("%4d. %-60s %10s\n", $num, $file['relative'], formatBytes($file['size']));
89 | }
90 |
91 | $output .= "\n" . str_repeat("=", 80) . "\n";
92 | $output .= " CONTENIDO DE LOS ARCHIVOS\n";
93 | $output .= str_repeat("=", 80) . "\n\n";
94 |
95 | foreach ($files as $index => $file) {
96 | $num = $index + 1;
97 | echo "Procesando ($num/$totalFiles): {$file['relative']}\n";
98 |
99 | $output .= "\n" . str_repeat("=", 80) . "\n";
100 | $output .= "ARCHIVO #$num: {$file['relative']}\n";
101 | $output .= str_repeat("=", 80) . "\n";
102 | $output .= "Ruta: {$file['path']}\n";
103 | $output .= "Tamaño: " . formatBytes($file['size']) . "\n";
104 | $output .= str_repeat("-", 80) . "\n\n";
105 |
106 | $content = file_get_contents($file['path']);
107 | $lines = explode("\n", $content);
108 | $lineCount = count($lines);
109 |
110 | foreach ($lines as $lineNum => $line) {
111 | $output .= sprintf("%5d | %s\n", $lineNum + 1, $line);
112 | }
113 |
114 | $output .= "\n" . str_repeat("-", 80) . "\n";
115 | $output .= "Total de líneas: $lineCount\n";
116 | $output .= str_repeat("=", 80) . "\n\n";
117 | }
118 |
119 | $output .= "\n" . str_repeat("=", 80) . "\n";
120 | $output .= " FIN DE LA DOCUMENTACIÓN\n";
121 | $output .= str_repeat("=", 80) . "\n\n";
122 |
123 | $output .= "Generado el: " . date('Y-m-d H:i:s') . "\n";
124 | $output .= "Total de archivos documentados: $totalFiles\n";
125 | $output .= "Tamaño total del código fuente: " . formatBytes($totalSize) . "\n\n";
126 |
127 | $output .= "Esta documentación ha sido generada para el registro del InTouch Framework\n";
128 | $output .= "en el Departamento de Derechos Intelectuales de Chile.\n\n";
129 |
130 | $output .= "Autor: Claudio Alfonso González Almeyda\n";
131 | $output .= "Copyright 2018 - 2025. Todos los derechos reservados.\n";
132 |
133 | file_put_contents($outputFile, $output);
134 |
135 | echo "\n";
136 | echo str_repeat("=", 80) . "\n";
137 | echo "Documentación generada exitosamente!\n";
138 | echo str_repeat("=", 80) . "\n";
139 | echo "Archivo: $outputFile\n";
140 | echo "Tamaño del archivo de documentación: " . formatBytes(filesize($outputFile)) . "\n";
141 | echo "Total de archivos documentados: $totalFiles\n";
142 | echo "Total de líneas de código: " . substr_count($output, "\n") . "\n";
143 | echo str_repeat("=", 80) . "\n";
144 |
--------------------------------------------------------------------------------
Total de líneas: 144
================================================================================
================================================================================
ARCHIVO #2: src/Annotation/AnnotationHelper.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Annotation/AnnotationHelper.php
Tamaño: 12.32 KB
--------------------------------------------------------------------------------
1 | __ClassAttributes;
28 | case "MethodAttributes": return $this->__MethodAttributes;
29 | case "PropertyAttributes": return $this->__PropertyAttributes;
30 | case "Reflected": return $this->__Reflected;
31 | default:
32 | user_error("Invalid property: " . __CLASS__ . "->$name");
33 | return null;
34 | }
35 |
36 | }
37 |
38 | private function __construct(public string $fullClassname) {
39 |
40 | $this->__ClassAttributes = null;
41 | $this->__MethodAttributes = [];
42 | $this->__PropertyAttributes = [];
43 |
44 | $this->__Reflected = new \ReflectionClass($fullClassname);
45 |
46 | $this->LoadAttributes();
47 | }
48 |
49 | public static function FromClass($fullClassname) {
50 | return new AnnotationHelper(fullClassname: $fullClassname);
51 | }
52 |
53 | public static function FromObject($object) {
54 | $classname = $object::class;
55 |
56 | return new AnnotationHelper(fullClassname: $classname);
57 | }
58 |
59 | private function LoadAttributes() {
60 |
61 | $this->__ClassAttributes = null;
62 | $this->__MethodAttributes = [];
63 | $this->__PropertyAttributes = [];
64 |
65 | $reflector = $this->__Reflected; // new \ReflectionClass($this->fullClassname);
66 |
67 | // Atributos de clase
68 | //
69 | $classContainer = new AttributeContainer(type: ContainerTypeEnum::TYPE_CLASS, name: $reflector->getShortName());
70 | $classAttributes = $reflector->getAttributes();
71 |
72 | if (isset($classAttributes) && $classAttributes !== false && is_array($classAttributes) && count($classAttributes) > 0) {
73 |
74 | // Instanciar cada atributo de clase encontrado para agregarlo a la coleccion
75 | //
76 | foreach($classAttributes as $classAttribute) {
77 | $instancia = $classAttribute->newInstance();
78 | if (isset($instancia)) {
79 | $classContainer->AddAttribute(name: $classAttribute->getName(), attribute: $instancia);
80 | }
81 | }
82 | }
83 |
84 | // Actualizar los atributos de clase actuales
85 | if (isset($classContainer))
86 | $this->__ClassAttributes = $classContainer;
87 |
88 |
89 | // Atributos de metodo
90 | //
91 | foreach ($reflector->getMethods() as $method) {
92 |
93 | if (isset($method) && isset($method->class) && $method->class == 'Intouch\Framework\Widget\Definitions\AmChart5\Data\DataCollection' ) {
94 | $stop = 1;
95 | }
96 |
97 | $methodType = $method->getReturnType();
98 |
99 | $methodContainer = new AttributeContainer(
100 | type: ContainerTypeEnum::TYPE_METHOD, name: $method->getName(),
101 | returnType: isset($methodType) ? $methodType->getName() : ''
102 | );
103 | $methodAttributes = $method->getAttributes();
104 |
105 | if (isset($methodAttributes) && $methodAttributes !== false && is_array($methodAttributes) && count($methodAttributes) > 0) {
106 |
107 | // Instanciar cada atributo de clase encontrado para agregarlo a la coleccion
108 | //
109 | foreach($methodAttributes as $methodAttribute) {
110 | $instancia = $methodAttribute->newInstance();
111 | if (isset($instancia)) {
112 | $methodContainer->AddAttribute(name: $methodAttribute->getName(), attribute: $instancia);
113 | }
114 | }
115 | }
116 |
117 | // Agregar los parametros del metodo al contenedor
118 | //
119 | $methodParameters = $method->getParameters();
120 |
121 | foreach($methodParameters as $methodParameter) {
122 | $methodContainer->AddParameter(
123 | $methodParameter->getName(),
124 | new MethodParameter(
125 | name: $methodParameter->getName(),
126 | type: ($methodParameter->hasType()) ? $methodParameter->getType()->getName() : "",
127 | allowsNull: $methodParameter->allowsNull(),
128 | defaultValue: ($methodParameter->isDefaultValueAvailable()) ? $methodParameter->getDefaultValue() : null,
129 | position: $methodParameter->getPosition(),
130 | isOptional: $methodParameter->isOptional()
131 | )
132 | );
133 | }
134 |
135 | // agregar el contenedor al listado, con el nombre del metodo
136 | if (isset($methodContainer))
137 | $this->__MethodAttributes[$method->getName()] = $methodContainer;
138 | }
139 |
140 | // Atributos de propiedades
141 | //
142 | foreach ($reflector->getProperties() as $property) {
143 |
144 | $propertyType = $property->getType();
145 |
146 | $propertyContainer = new AttributeContainer(
147 | type: ContainerTypeEnum::TYPE_PROPERTY, name: $property->getName(),
148 | dataType: isset($propertyType) ? $propertyType->getName() : ''
149 | );
150 | $propertyAttributes = $property->getAttributes();
151 |
152 | if (isset($propertyAttributes) && $propertyAttributes !== false && is_array($propertyAttributes) && count($propertyAttributes) > 0) {
153 |
154 | // Instanciar cada atributo de clase encontrado para agregarlo a la coleccion
155 | //
156 | foreach($propertyAttributes as $propertyAttribute) {
157 | $instancia = $propertyAttribute->newInstance();
158 | if (isset($instancia)) {
159 | $propertyContainer->AddAttribute(name: $propertyAttribute->getName(), attribute: $instancia);
160 | }
161 | }
162 | }
163 |
164 | // agregar el contenedor al listado, con el nombre del metodo
165 | if (isset($propertyContainer))
166 | $this->__PropertyAttributes[$property->getName()] = $propertyContainer;
167 | }
168 | }
169 |
170 | /**
171 | * Obtiene una colección con todas las propiedades que tienen el atributo especificado
172 | *
173 | * @param string $fullAtrributeClassname El nombre de clase del atributo buscado
174 | *
175 | * @return GenericCollection
176 | */
177 | public function GetAttributeProperties(string $fullAtrributeClassname) {
178 |
179 | $results = array();
180 |
181 | // Verificar si existen propiedades
182 | //
183 | if (isset($this->__PropertyAttributes) || count($this->__PropertyAttributes) > 0) {
184 |
185 | // Recorrer las propiedades y recopilar aquellas que tengan el atributo buscado
186 | //
187 | foreach($this->__PropertyAttributes as $propertyName => $attributeContainer) {
188 | foreach($attributeContainer->Attributes as $attributeName => $attribute) {
189 | if ($attributeName == $fullAtrributeClassname) {
190 | array_push($results, new PropertyAttribute(propertyName: $propertyName, attribute: $attribute));
191 | break;
192 | }
193 | }
194 | }
195 |
196 | }
197 |
198 | if (count($results) > 0)
199 | return new GenericCollection(
200 | DtoName: PropertyAttribute::class,
201 | Key: 'propertyName',
202 | Values: $results
203 | );
204 | else
205 | return null;
206 | }
207 |
208 | /**
209 | * Obtiene la propiedad que contenga el atributo especificado. Si hay más de una, devuelve la primera encontrada
210 | *
211 | * @param string $fullAtrributeClassname El nombre de clase del atributo buscado
212 | *
213 | * @return Collection
214 | */
215 | public function FindAttributeProperty(string $fullAttributeClassname) {
216 |
217 | $attributes = $this->GetAttributeProperties($fullAttributeClassname);
218 |
219 | if (isset($attributes) && $attributes->Count() > 0) {
220 | return $attributes->First();
221 | }
222 |
223 | return null;
224 | }
225 |
226 | /**
227 | * Obtiene una colección con todos los metodos que tienen el atributo especificado
228 | *
229 | * @param string $fullAtrributeClassname El nombre de clase del atributo buscado
230 | *
231 | * @return Collection
232 | */
233 | public function GetAttributeMethods(string $fullAttributeClassname) {
234 |
235 | $results = array();
236 |
237 | // Verificar si existen metodos
238 | //
239 | if (isset($this->__MethodAttributes) || count($this->__MethodAttributes) > 0) {
240 |
241 | // Recorrer los metodos y recopilar aquellos que tengan el atributo buscado
242 | //
243 | foreach($this->__MethodAttributes as $methodName => $attributeContainer) {
244 | foreach($attributeContainer->Attributes as $attributeName => $attribute) {
245 | if ($attributeName == $fullAttributeClassname) {
246 | array_push($results, new MethodAttribute(methodName: $methodName, methodParameters: $attributeContainer->Parameters, attribute: $attribute));
247 | break;
248 | }
249 | }
250 | }
251 |
252 | }
253 |
254 | if (count($results) > 0)
255 | return new GenericCollection(
256 | Key: 'methodName',
257 | DtoName: MethodAttribute::class,
258 | Values: $results
259 | );
260 | else
261 | return null;
262 | }
263 |
264 |
265 | public function GetMethodAttributes(MethodAttribute $method) : AttributeContainer {
266 |
267 | if (isset($this->__MethodAttributes[$method->methodName])) {
268 | return $this->__MethodAttributes[$method->methodName];
269 | }
270 | else {
271 | return null;
272 | }
273 | }
274 |
275 | /**
276 | * Obtiene el metodo que contenga el atributo especificado. Si hay más de uno, devuelve el primero encontrado
277 | *
278 | * @param string $fullAtrributeClassname El nombre de clase del atributo buscado
279 | *
280 | * @return Collection
281 | */
282 | public function FindAttributeMethod(string $fullAttributeClassname) {
283 |
284 | $attributes = $this->GetAttributeMethods($fullAttributeClassname);
285 |
286 | if (isset($attributes) && $attributes->Count() > 0) {
287 | return $attributes->First();
288 | }
289 |
290 | return null;
291 | }
292 |
293 | public function MethodHasAttribute(string $method, string $fullAttributeClassname): bool {
294 |
295 | $results = array();
296 |
297 | // Verificar si existen metodos
298 | //
299 | if (isset($this->__MethodAttributes) || count($this->__MethodAttributes) > 0) {
300 |
301 | // Recorrer los metodos y encontrar el metodo buscado, y verificar si tiene el atributo
302 | //
303 | foreach($this->__MethodAttributes as $methodName => $attributeContainer) {
304 |
305 | if (strtolower($methodName) == strtolower($method)) {
306 | foreach($attributeContainer->Attributes as $attributeName => $attribute) {
307 | if ($attributeName == $fullAttributeClassname) {
308 | return true;
309 | }
310 | }
311 | }
312 | }
313 |
314 | }
315 |
316 | return false;
317 |
318 | }
319 |
320 | public function FindAttributeClass($fullAttributeClassname) {
321 |
322 | $results = array();
323 |
324 | // Verificar si existen attributos de clase
325 | //
326 | if (isset($this->__ClassAttributes->Attributes) || count($this->__ClassAttributes->Attributes) > 0) {
327 |
328 | // Recorrer los atributos de la clase y verificar si existe el atributo buscado
329 | //
330 | foreach($this->__ClassAttributes->Attributes as $attributeName => $attribute) {
331 | if ($attributeName == $fullAttributeClassname) {
332 | array_push($results, new ClassAttribute(className: $this->fullClassname, attribute: $attribute));
333 | break;
334 | }
335 | }
336 |
337 | }
338 |
339 | if (count($results) > 0)
340 | return $results[0];
341 | else
342 | return null;
343 | }
344 |
345 | public function Exists(string $property, string $attribute) {
346 |
347 | if (isset($this->__PropertyAttributes[$property]) && $this->__PropertyAttributes[$property]->HasAttribute($attribute)) {
348 | return true;
349 | }
350 | else {
351 | return false;
352 | }
353 | }
354 |
355 | }
--------------------------------------------------------------------------------
Total de líneas: 355
================================================================================
================================================================================
ARCHIVO #3: src/Annotation/AttributeContainer.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Annotation/AttributeContainer.php
Tamaño: 1.87 KB
--------------------------------------------------------------------------------
1 | __Type;
28 | case "Name": return $this->__Name;
29 | case "ReturnType": return $this->__ReturnType;
30 | case "DataType": return $this->__DataType;
31 | case "Attributes": return $this->__Attributes;
32 | case "Parameters": return $this->__Parameters;
33 | default:
34 | user_error("Invalid property: " . __CLASS__ . "->$name");
35 | return null;
36 | }
37 |
38 | }
39 |
40 | public function AddAttribute($name, $attribute) {
41 | $this->__Attributes[$name] = $attribute;
42 | }
43 |
44 | public function AddParameter(string $name, MethodParameter $parameter) {
45 | $this->__Parameters[$name] = $parameter;
46 | }
47 |
48 | public function __construct(
49 | int $type, string $name, string $returnType = '', string $dataType = ''
50 | ) {
51 | $this->__Type = $type;
52 | $this->__Name = $name;
53 | $this->__ReturnType = $returnType;
54 | $this->__DataType = $dataType;
55 | }
56 |
57 | public function HasAttribute(string $fullAtrributeClassname) {
58 |
59 | foreach($this->__Attributes as $attribueName => $attribute) {
60 | if ($attribueName == $fullAtrributeClassname)
61 | return true;
62 | }
63 |
64 | return false;
65 | }
66 | }
--------------------------------------------------------------------------------
Total de líneas: 66
================================================================================
================================================================================
ARCHIVO #4: src/Annotation/Attributes/CacheMulti.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Annotation/Attributes/CacheMulti.php
Tamaño: 380 bytes
--------------------------------------------------------------------------------
1 | uri = $this->GetImageUri($asset);
60 | }
61 | else if ($asset instanceof PdfResource) {
62 | $asset->uri = $this->GetPdfUri($asset);
63 | }
64 |
65 | return $asset;
66 | }
67 |
68 | function GetImageUri(ImageResource $asset): null|string {
69 |
70 | $resource = new \stdClass();
71 | $resource->bucket = "website-assets-shutdown-cl";
72 | $resource->key = $this->mainFolder . ( ($asset->location != '') ? '/' . $asset->location : '');
73 |
74 | if ($asset->width > 0) {
75 | $resource->edits = new \stdClass();
76 | $resource->edits->resize = new \stdClass();
77 | $resource->edits->resize->width = 100;
78 | $resource->edits->resize->fit = "inside";
79 | }
80 |
81 | $json = str_replace("\\", "", json_encode($resource));
82 | $encoded = base64_encode($json);
83 |
84 | return $this->apiEndpoint . '/' . $encoded;
85 | }
86 |
87 | function GetPdfUri(PdfResource $asset): null|string {
88 |
89 | $endpoint = $this->apiEndpoint . '/' . $asset->location;
90 |
91 | // Construct the CloudFront request
92 | return null;
93 | }
94 |
95 | private function SolicitarRecurso($ruta) {
96 |
97 | }
98 | }
--------------------------------------------------------------------------------
Total de líneas: 98
================================================================================
================================================================================
ARCHIVO #36: src/Assets/Managers/LocalAssetManager.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Assets/Managers/LocalAssetManager.php
Tamaño: 1.29 KB
--------------------------------------------------------------------------------
1 | rootPath . '/' . $asset->location . '/' . $asset->name;
42 |
43 | if (file_exists($path)) {
44 | $content = file_get_contents($path);
45 | $asset->content = $content;
46 | }
47 | else {
48 | $asset->content = null;
49 | }
50 |
51 | return $asset;
52 | }
53 |
54 | /**
55 | *
56 | * @param Resource $asset
57 | *
58 | * @return Resource
59 | */
60 | function GetAssetUri(Resource $asset): Resource {
61 | $asset->uri = $this->rootUri . '/' . $asset->location . '/' . $asset->name;
62 |
63 | return $asset;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
Total de líneas: 66
================================================================================
================================================================================
ARCHIVO #37: src/Assets/Managers/S3AssetManager.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Assets/Managers/S3AssetManager.php
Tamaño: 1.54 KB
--------------------------------------------------------------------------------
1 | __content;
22 | case "uri": return $this->__uri;
23 | default:
24 | user_error("Invalid property: " . __CLASS__ . "->$name");
25 | return null;
26 | }
27 |
28 | }
29 |
30 | function __set($name, $value) {
31 |
32 | switch($name) {
33 | case "content":
34 | $this->__content = $value;
35 | break;
36 | case "uri":
37 | $this->__uri = $value;
38 | break;
39 | default:
40 | user_error("Invalid property: " . __CLASS__ . "->$name");
41 | return null;
42 | }
43 |
44 | }
45 | public function __construct(
46 | public string $id,
47 | public string $name,
48 | public string $localpath = '',
49 | public string $location = ''
50 | ) {}
51 |
52 | }
--------------------------------------------------------------------------------
Total de líneas: 52
================================================================================
================================================================================
ARCHIVO #40: src/BLL/DataTransferObjects/RangoDto.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/BLL/DataTransferObjects/RangoDto.php
Tamaño: 368 bytes
--------------------------------------------------------------------------------
1 | Dao = $dao;
32 | $this->DtoName = $dtoName;
33 | $this->EntityName = $entityName;
34 | }
35 |
36 | public function GetDomain()
37 | {
38 | return $this->Dao->Domain;
39 | }
40 |
41 | public function GetDtoName()
42 | {
43 | return $this->DtoName;
44 | }
45 |
46 |
47 | public static function BeginMultipleOperations($domain, $transactionLevel = null)
48 | {
49 | // Obtener una transaccion
50 | self::$Transaction = ExecuteDao::OpenTransaction($domain, $transactionLevel);
51 |
52 | if (isset(self::$Transaction)) {
53 | return true;
54 | } else {
55 | return false;
56 | }
57 | }
58 |
59 | public static function SaveMultipleOperations()
60 | {
61 | ExecuteDao::CommitTransaction(self::$Transaction);
62 | self::$Transaction = null;
63 | }
64 |
65 | public static function UndoMultipleOperations()
66 | {
67 | ExecuteDao::RollbackTransaction(self::$Transaction);
68 | self::$Transaction = null;
69 | }
70 |
71 | public function Find($keyValue, $incluirNoVigentes = true, $incluirEliminados = true, $nosanear = false)
72 | {
73 | $dto = Mapper::ToDto($this->Dao->Find($keyValue, $incluirNoVigentes, $incluirEliminados, GenericSvc::$Transaction), $this->DtoName, [], $nosanear);
74 | return $dto;
75 | }
76 |
77 | public function FindBy($bindings, $orderFields = '', $nosanear = false)
78 | {
79 | return Mapper::ToDto($this->Dao->FindBy($bindings, $orderFields, GenericSvc::$Transaction), $this->DtoName, [], $nosanear);
80 | }
81 |
82 | public function FindByForeign($foreignKey, $foreignKeyValue, $nosanear = false)
83 | {
84 | return Mapper::ToDto($this->Dao->FindByForeign($foreignKey, $foreignKeyValue, GenericSvc::$Transaction), $this->DtoName, [], $nosanear);
85 | }
86 |
87 | public function GetAll($order = "", $avoidNull = false, $nosanear = false)
88 | {
89 | return Mapper::ToDtos(entityArray: $this->Dao->GetAll($order, GenericSvc::$Transaction), dtoName: $this->DtoName, avoidNull: $avoidNull, nosanear: $nosanear);
90 | }
91 |
92 | public function GetBy($bindings, $orderFields = '', $avoidNull = false, $top = 0, $nosanear = false, $aplicarTope = true, $ramSinTope = IniEnum::MEM_2G)
93 | {
94 | return Mapper::ToDtos(entityArray: $this->Dao->GetBy($bindings, $orderFields, $top, GenericSvc::$Transaction), dtoName: $this->DtoName, avoidNull: $avoidNull, nosanear: $nosanear, aplicarTope: $aplicarTope, ramSinTope: $ramSinTope);
95 | }
96 |
97 | public function GetByToFile($bindings, $orderFields = '', $top = 0, $localDataFolder = "") {
98 |
99 | return $this->Dao->GetByToFile($bindings, $orderFields, $top, GenericSvc::$Transaction, $localDataFolder);
100 |
101 | }
102 |
103 |
104 | public function GetByForeign($foreignKey, $foreignKeyValue, $orderFields = '', $avoidNull = false, $nosanear = false)
105 | {
106 | return Mapper::ToDtos(entityArray: $this->Dao->GetByForeign($foreignKey, $foreignKeyValue, $orderFields, GenericSvc::$Transaction), dtoName: $this->DtoName, avoidNull: $avoidNull, nosanear: $nosanear);
107 | }
108 |
109 | public function GetByCodigoRegistro($codigoRegistro, $avoidNull = false)
110 | {
111 | return Mapper::ToDtos(entityArray: $this->Dao->GetByCodigoRegistro($codigoRegistro, GenericSvc::$Transaction), dtoName: $this->DtoName, avoidNull: $avoidNull);
112 | }
113 |
114 | public function Insert($dto, $nosanear = false, ?IAuditable $auditable = null)
115 | {
116 | if ($this->DtoName !== get_class($dto)) {
117 | throw new \Exception('El DTO a insertar debe ser una instancia de la clase: ' . $this->DtoName);
118 | return null;
119 | }
120 |
121 | return Mapper::ToDto($this->Dao->Insert(Mapper::ToEntity($dto, $this->EntityName, false, $nosanear), GenericSvc::$Transaction, $auditable), $this->DtoName);
122 | }
123 |
124 | public function Update($dto, $nosanear = false, ?IAuditable $auditable = null)
125 | {
126 | if ($this->DtoName !== get_class($dto)) {
127 | throw new \Exception('El DTO a insertar debe ser una instancia de la clase: ' . $this->DtoName);
128 | return null;
129 | }
130 |
131 | $this->Dao->Update(Mapper::ToEntity($dto, $this->EntityName, false, $nosanear), GenericSvc::$Transaction, $auditable);
132 | }
133 |
134 | public function Delete($keyValue)
135 | {
136 | $this->Dao->Delete($keyValue, GenericSvc::$Transaction);
137 | }
138 |
139 | public function LogicDelete($keyValue)
140 | {
141 | $this->Dao->LogicDelete($keyValue, GenericSvc::$Transaction);
142 | }
143 |
144 | public function DeleteBy($bindings)
145 | {
146 | $this->Dao->DeleteBy($bindings, GenericSvc::$Transaction);
147 | }
148 |
149 | public function LogicDeleteBy($bindings)
150 | {
151 | $this->Dao->LogicDeleteBy($bindings, GenericSvc::$Transaction);
152 | }
153 |
154 | public function Count()
155 | {
156 | return $this->Dao->Count(GenericSvc::$Transaction);
157 | }
158 |
159 | public function CountBy($bindings)
160 | {
161 | return $this->Dao->CountBy($bindings, GenericSvc::$Transaction);
162 | }
163 |
164 | function SumFieldByForeign($fieldName, $foreignKeyName, $foreignKeyValue)
165 | {
166 | return $this->Dao->SumFieldByForeign($fieldName, $foreignKeyName, $foreignKeyValue, GenericSvc::$Transaction);
167 | }
168 |
169 | function CountByForeign($foreignKeyName, $foreignKeyValue)
170 | {
171 | return $this->Dao->CountByForeign($foreignKeyName, $foreignKeyValue, GenericSvc::$Transaction);
172 | }
173 |
174 | function Query(Queryable $query, bool $returnFirstRecord = false, $avoidNull = false)
175 | {
176 | return Mapper::GetInstance()->map($this->Dao->Query($query, $returnFirstRecord, GenericSvc::$Transaction), null, true, '', true, $avoidNull);
177 | }
178 |
179 | function GetIN($foreignKey, $foreignKeyValue, $orderFields = '')
180 | {
181 | //return $this->Dao->GetIN($foreignKey, $foreignKeyValue, $orderFields);
182 | return Mapper::ToDtos($this->Dao->GetIN($foreignKey, $foreignKeyValue, $orderFields, GenericSvc::$Transaction), $this->DtoName);
183 | }
184 |
185 | public function Max($field, $ignoreBlanks = false)
186 | {
187 | return $this->Dao->Max($field, ignoreBlanks: $ignoreBlanks, transaction: GenericSvc::$Transaction);
188 | }
189 |
190 | public function Min($field, $ignoreBlanks = false)
191 | {
192 | return $this->Dao->Min(field: $field, ignoreBlanks: $ignoreBlanks, transaction: GenericSvc::$Transaction);
193 | }
194 |
195 | public function Rango($field, $ignoreBlanks = false)
196 | {
197 |
198 | $menor = $this->Dao->Min($field, $ignoreBlanks);
199 | $mayor = $this->Dao->Max($field, $ignoreBlanks);
200 |
201 | if (!isset($menor)) $menor = 0;
202 | if (!isset($mayor)) $mayor = 0;
203 |
204 | return new RangoDto(
205 | Menor: $menor,
206 | Mayor: $mayor
207 | );
208 | }
209 | }
210 |
--------------------------------------------------------------------------------
Total de líneas: 210
================================================================================
================================================================================
ARCHIVO #44: src/BLL/WebService/HttpHelper.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/BLL/WebService/HttpHelper.php
Tamaño: 5.23 KB
--------------------------------------------------------------------------------
1 | > <
>
21 |
22 | // Obtener los parametros
23 | if (isset($argc) && $argc >= 4) {
24 | $engine = new Engine(
25 | entityDomain: $argv[1],
26 | entityNamespace: $argv[2],
27 | entityTable: $argv[3]
28 | );
29 |
30 | $overwrite = false;
31 | if ($argc >= 5) {
32 | if (trim($argv[4]) == 'overwrite') {
33 | $overwrite = true;
34 | }
35 | }
36 |
37 | $engine->Generate($overwrite);
38 | }
39 | else {
40 | echo "\nError: parámetros no válidos\n\n";
41 | echo "Usage: ./gen.sh <> <> <> [[overwrite]]\n";
42 | echo "\nEjs:\n./gen.sh default Administracion TipoCliente,TipoProducto\n./gen.sh default Administracion TipoCliente,Cuenta,Usuario overwrite\n\n";
43 | die();
44 | }
--------------------------------------------------------------------------------
Total de líneas: 44
================================================================================
================================================================================
ARCHIVO #48: src/Bin/mantenedor.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Bin/mantenedor.php
Tamaño: 1.27 KB
--------------------------------------------------------------------------------
1 | > <>
21 |
22 | // Obtener los parametros
23 | if (isset($argc) && $argc >= 4) {
24 | $engine = new Engine(
25 | entityDomain: $argv[1],
26 | entityNamespace: $argv[2],
27 | entityTable: $argv[3]
28 | );
29 |
30 | $overwrite = false;
31 | if ($argc >= 5) {
32 | if (trim($argv[4]) == 'overwrite') {
33 | $overwrite = true;
34 | }
35 | }
36 |
37 | $engine->Mantenedor($overwrite);
38 | }
39 | else {
40 | echo "\nError: parámetros no válidos\n\n";
41 | echo "Usage: ./gen.sh <> <> <> [[overwrite]]\n";
42 | echo "\nEjs:\n./gen.sh default Administracion TipoCliente,TipoProducto\n./gen.sh default Administracion TipoCliente,Cuenta,Usuario overwrite\n\n";
43 | die();
44 | }
--------------------------------------------------------------------------------
Total de líneas: 44
================================================================================
================================================================================
ARCHIVO #49: src/Cache/Page.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Cache/Page.php
Tamaño: 25.80 KB
--------------------------------------------------------------------------------
1 | (int)$draw, // Castear a int por seguridad
105 | "recordsTotal" => $pageResults->RecordCount, // $recordsTotal,
106 | "recordsFiltered" => $pageResults->RecordCount, // $recordsFiltered,
107 | "data" => $pageResults->Data, // $data,
108 | // El campo "error" no se incluirá si no hay mensajes de error explícitos.
109 | ];
110 |
111 | // Retornar la respuesta como un string JSON.
112 | return json_encode($response);
113 | }
114 |
115 | /**
116 | * Recupera un segmento paginado de resultados desde Redis.
117 | * Refresca el TTL de todas las llaves (índice y chunks) asociadas al conjunto de resultados
118 | * si el índice principal indica que se debe hacer.
119 | *
120 | * @param string $resultsId El GUID del conjunto de resultados principal.
121 | * @param int $pageNumber El número de página a recuperar (base 1).
122 | * @param int $recordsPerPage La cantidad de registros por página.
123 | * @return PageResults Un arreglo con los registros de la página solicitada.
124 | * @throws Exception Si ocurre un error crítico que impide la recuperación de los datos.
125 | */
126 | public static function GetResults(string $resultsId, int $pageNumber, ?int $recordsPerPage=0): PageResults
127 | {
128 | $result = new PageResults(
129 | ResultsId: $resultsId
130 | );
131 |
132 | // 1. Obtener la instancia de Redis
133 | try {
134 | $redis = RedisSvc::Init();
135 | } catch (Throwable $e) { // Captura cualquier excepción de conexión de RedisSvc::Init()
136 | throw new Exception("Error al conectar a Redis para GetResults: " . $e->getMessage(), 0, $e);
137 | }
138 |
139 | // 2. Construir la llave del índice principal
140 | $indexKey = "{$resultsId}_resultindex";
141 |
142 | // 3. Recuperar y deserializar el índice principal
143 | $indexData =self::GetIndex($resultsId);
144 |
145 | // $serializedIndex = $redis->get($indexKey);
146 |
147 | // if ($serializedIndex === false) {
148 | // // El índice no existe o ya expiró. Esto es una condición esperada, no un error de sistema.
149 | // return $result;
150 | // }
151 |
152 | // $indexData = json_decode($serializedIndex, true);
153 |
154 | // if (json_last_error() !== JSON_ERROR_NONE) {
155 | // throw new Exception("Error al deserializar el índice de resultados '$indexKey': " . json_last_error_msg());
156 | // }
157 |
158 | // // Validar que los datos esenciales estén presentes en el índice
159 | // if (!isset($indexData['RecordCount'], $indexData['ChunkSize'], $indexData['Llaves'], $indexData['ChunkTtl'], $indexData['ChunkTtlRefresh'])) {
160 | // throw new Exception("Índice de resultados '$indexKey' incompleto o malformado.");
161 | // }
162 |
163 | // $recordCount = (int) $indexData['RecordCount'];
164 | // $chunkSize = (int) $indexData['ChunkSize'];
165 | // $allChunkKeys = (array) $indexData['Llaves'];
166 | // $chunkTtl = (int) $indexData['ChunkTtl'];
167 | // $chunkTtlRefresh = (int) $indexData['ChunkTtlRefresh']; // 0 o 1
168 | $recordCount = $indexData->RecordCount;
169 | $chunkSize = $indexData->ChunkSize;
170 | $allChunkKeys = $indexData->Llaves;
171 | $chunkTtl = $indexData->ChunkTtl;
172 | $chunkTtlRefresh = $indexData->ChunkTtlRefresh; // 0 o 1
173 |
174 | // 4. Refrescar el TTL de la llave del índice (siempre)
175 | if (!$redis->expire($indexKey, $chunkTtl)) {
176 | // No lanzamos excepción aquí, ya que el fallo en el refresh del TTL no impide obtener los datos
177 | // pero es un problema digno de loggear para monitoreo.
178 | error_log("ADVERTENCIA: No se pudo refrescar el TTL de la llave del índice: '$indexKey'");
179 | }
180 |
181 | // 5. Calcular el rango de registros necesario para la página
182 | if ($pageNumber >= 0) {
183 | $startIndex = ($pageNumber - 1) * $recordsPerPage;
184 |
185 | // Asegurarse de que el número de página sea válido y que los registros no excedan el total
186 | if ($pageNumber < 1 || $startIndex >= $recordCount) {
187 | return $result; // Página fuera de rango o sin registros - esto es un caso de negocio, no un error.
188 | }
189 |
190 | $endIndex = min($startIndex + $recordsPerPage - 1, $recordCount - 1); // El último índice de registro de la página
191 | $recordsToFetchCount = $endIndex - $startIndex + 1; // Cantidad exacta de registros a recuperar para esta página
192 |
193 | // 6. Identificar los chunks que necesitamos (y todos los demás para el refresh)
194 | // 6. Calcular qué chunks específicos necesitamos cargar
195 | $firstChunkIndex = floor($startIndex / $chunkSize);
196 | $lastChunkIndex = floor($endIndex / $chunkSize);
197 | }
198 | else {
199 | $startIndex = 0;
200 | $endIndex = $recordCount-1;
201 | }
202 |
203 | $relevantChunkKeys = [];
204 | for ($i = $firstChunkIndex; $i <= $lastChunkIndex; $i++) {
205 | // Aquí es crucial que tengas un patrón para tus claves de chunk
206 | // Por ejemplo, si tus claves son 'resultados:chunk:0', 'resultados:chunk:1', etc.
207 | // Necesitas reconstruirlas o tener un array mapeado por índice.
208 | // Para este ejemplo, asumiremos que $allChunkKeys está indexado o podemos generar la clave.
209 | // Si tus claves no son secuenciales o predecibles, necesitarás una lógica diferente para obtenerlas.
210 |
211 | // Suponiendo que $allChunkKeys contiene las claves ordenadas por índice.
212 | // Si no es el caso, deberías tener una forma de generar la clave dado el índice del chunk,
213 | // por ejemplo, $chunkKey = "prefijo:chunk:" . $i;
214 |
215 | if (isset($allChunkKeys[$i])) {
216 | $relevantChunkKeys[] = $allChunkKeys[$i];
217 | } else {
218 | // Esto indica un problema grave: el chunk esperado no existe en la lista de claves.
219 | // Podría ser un desincronización o un error en la generación de claves.
220 | throw new Exception("Chunk clave para el índice {$i} no encontrado. El conjunto de resultados podría estar incompleto.");
221 | }
222 | }
223 |
224 | $allRecords = []; // Aquí se acumularán todos los registros de los chunks recuperados
225 |
226 | foreach ($relevantChunkKeys as $chunkKey) {
227 | $serializedChunk = $redis->get($chunkKey);
228 |
229 | if ($serializedChunk === false) {
230 | // Si un chunk no se encuentra, es un problema.
231 | // Podría ser por expiración prematura, o una inconsistencia.
232 | throw new Exception("Chunk de resultados '$chunkKey' no encontrado o expirado. El conjunto de resultados podría estar incompleto.");
233 | }
234 |
235 | $chunkData = json_decode($serializedChunk, true);
236 |
237 | if (json_last_error() !== JSON_ERROR_NONE) {
238 | throw new Exception("Error al deserializar chunk de resultados '$chunkKey': " . json_last_error_msg());
239 | }
240 |
241 | // Refrescar el TTL del chunk si ChunkTtlRefresh está activado
242 | if ($chunkTtlRefresh === 1) {
243 | if (!$redis->expire($chunkKey, $chunkTtl)) {
244 | // Similar al índice, loggeamos la advertencia si el refresh falla.
245 | error_log("ADVERTENCIA: No se pudo refrescar el TTL del chunk: '$chunkKey'");
246 | }
247 | }
248 |
249 | // Acumular los registros de este chunk
250 | if (is_array($chunkData)) {
251 | $allRecords = array_merge($allRecords, $chunkData);
252 | } else {
253 | // Si el chunk no contiene un arreglo, es un dato corrupto
254 | throw new Exception("El chunk '$chunkKey' no contenía un arreglo de registros como se esperaba.");
255 | }
256 | }
257 |
258 | // 7. Extraer solo los registros de la página solicitada del arreglo combinado
259 | $offsetInLoadedRecords = $startIndex - ($firstChunkIndex * $chunkSize);
260 | $paginatedResults = array_slice($allRecords, $offsetInLoadedRecords, $recordsToFetchCount);
261 |
262 |
263 | $result->RecordCount = $recordCount;
264 | $result->RecordsFiltered = count($paginatedResults);
265 | $result->Data = $paginatedResults;
266 |
267 | return $result;
268 | }
269 |
270 | public static function GetIndex(string $resultsId) {
271 |
272 | if (isset(self::$index)) {
273 | return self::$index;
274 | }
275 |
276 | // 1. Obtener la instancia de Redis
277 | try {
278 | $redis = RedisSvc::Init();
279 | } catch (Throwable $e) { // Captura cualquier excepción de conexión de RedisSvc::Init()
280 | throw new Exception("Error al conectar a Redis para GetResults: " . $e->getMessage(), 0, $e);
281 | }
282 |
283 | // 2. Construir la llave del índice principal
284 | $indexKey = "{$resultsId}_resultindex";
285 |
286 | // 3. Recuperar y deserializar el índice principal
287 | $serializedIndex = $redis->get($indexKey);
288 |
289 | if ($serializedIndex === false) {
290 | // El índice no existe o ya expiró. Esto es una condición esperada, no un error de sistema.
291 | return null;
292 | }
293 |
294 | $indexData = json_decode($serializedIndex, true);
295 |
296 | if (json_last_error() !== JSON_ERROR_NONE) {
297 | throw new Exception("Error al deserializar el índice de resultados '$indexKey': " . json_last_error_msg());
298 | }
299 |
300 | // Mapear
301 | // autoMapper($sourceObject, $targetObject, $nosanear = false, $honorPrefix = '', $useTargetProperties = false, array $innerMappings = [])
302 | $pageDef = PageDefinition::NewFromIndex((object)$indexData);
303 |
304 | if ($pageDef instanceof PageDefinition) {
305 | if (!isset($pageDef->RecordCount, $pageDef->ChunkSize, $pageDef->Llaves, $pageDef->ChunkTtl, $pageDef->ChunkTtlRefresh)) {
306 | throw new Exception("Índice de resultados '$indexKey' incompleto o malformado.");
307 | }
308 | }
309 | else {
310 | throw new Exception("Índice de resultados '$indexKey' no es del tipo esperado.");
311 | }
312 |
313 | return $pageDef;
314 | }
315 |
316 | /**
317 | * Almacena un arreglo completo de resultados en Redis, dividiéndolo en "chunks"
318 | * para optimizar la recuperación paginada.
319 | *
320 | * Este método genera un GUID único para el conjunto de resultados, serializa los datos,
321 | * y los guarda en Redis usando pipelining para mayor eficiencia. Crea un índice principal
322 | * con metadata y llaves de los chunks, aplicando el TTL definido.
323 | *
324 | * @param array $results El arreglo completo de registros a almacenar. Cada elemento debe ser serializable a JSON.
325 | * @return PageDefinition Un objeto PageDefinition con los detalles de la paginación y el estado de la inserción.
326 | * @throws Exception Si falla la conexión a Redis, la serialización de datos, o la inserción en Redis.
327 | * @throws InvalidArgumentException Si los datos de entrada no son válidos (ej. $results no es un arreglo).
328 | */
329 | public static function PutResults(array|GenericCollection $results, ?string $dtoName = '', $key = '', $orderColumn = '', $orderDir = 'asc'): PageDefinition
330 | {
331 | if (empty($results) || (is_array($results) && count($results) == 0)) {
332 | // Se podría lanzar una excepción si no se permite insertar arreglos vacíos.
333 | // Para este caso, podemos simplemente crear un índice vacío.
334 | // throw new InvalidArgumentException("El arreglo de resultados no puede estar vacío.");
335 | }
336 |
337 |
338 | if (is_array($results)) {
339 | if ($dtoName == '') {
340 | throw new Exception("Debe especificar el nombre del DTO (dtoName) cuando no usa GenericCollection");
341 | }
342 | }
343 | else if ($results instanceof GenericCollection) {
344 | $dtoName = $results->GetDtoName();
345 | $results = $results->Values;
346 | }
347 | else {
348 | if ($dtoName == '') {
349 | throw new Exception("Debe especificar el nombre del DTO (dtoName) cuando no usa GenericCollection");
350 | }
351 | }
352 |
353 | // 1. Obtener la instancia de Redis y preparar IDs y metadata
354 | try {
355 | $redis = RedisSvc::Init();
356 | } catch (Throwable $e) {
357 | throw new Exception("Error al conectar a Redis para PutResults: " . $e->getMessage(), 0, $e);
358 | }
359 |
360 | // Importante: Asegúrate de que _guid() sea robusta (ej. usando random_bytes o Ramsey\Uuid)
361 | $resultsId = _guid(); // Genera un GUID único para el conjunto de resultados
362 | $idResultIndex = $resultsId . "_resultindex"; // Llave para el índice principal
363 | $idResultPrefix = $resultsId . "_results_"; // Prefijo para las llaves de los chunks
364 |
365 | $recordCount = count($results);
366 | $chunks = array_chunk($results, self::$CHUNK_SIZE);
367 | $chunkLength = count($chunks);
368 | $llaves = []; // Array para almacenar las llaves de los chunks creados
369 |
370 | // 2. Preparar el índice principal (metadata)
371 | $resultIndex = new PageDefinition(
372 | ResultsId : $resultsId,
373 | DtoName : $dtoName,
374 | Key : $key,
375 | OrderColumn : $orderColumn,
376 | OrderDir : $orderDir,
377 | InsertStatus : false,
378 | RecordCount : $recordCount,
379 | ChunkSize : self::$CHUNK_SIZE,
380 | ChunkLength : $chunkLength,
381 | ChunkTtl : self::$CHUNK_TTL,
382 | ChunkTtlRefresh : self::$CHUNK_TTL_REFRESH,
383 | Llaves : [],
384 | );
385 |
386 | // $resultIndex = [
387 | // "ResultsId" => $resultsId,
388 | // "DtoName" => $dtoName,
389 | // "InsertStatus" => false, // Se actualiza al final si todo es exitoso
390 | // "RecordCount" => $recordCount,
391 | // "ChunkSize" => self::$CHUNK_SIZE,
392 | // "ChunkLength" => $chunkLength,
393 | // "ChunkTtl" => self::$CHUNK_TTL,
394 | // "ChunkTtlRefresh" => self::$CHUNK_TTL_REFRESH,
395 | // "Llaves" => [], // Se llenará en el pipeline
396 | // ];
397 |
398 | // 3. Usar Pipelining para insertar todos los chunks y el índice atómicamente/eficientemente
399 | try {
400 | // Iniciar el pipeline
401 | $redis->multi(Redis::PIPELINE);
402 |
403 | // Generar y serializar los chunks, y añadir comandos SET al pipeline
404 | foreach ($chunks as $idx => $chunk) {
405 | $chunkKey = $idResultPrefix . $idx;
406 | $llaves[] = $chunkKey; // Acumular llaves para el índice
407 |
408 | $serializedChunk = json_encode($chunk);
409 | if ($serializedChunk === false) {
410 | // Descartar el pipeline si la serialización de un chunk falla
411 | $redis->discard();
412 | throw new Exception("Error al serializar el chunk {$idx} para Redis: " . json_last_error_msg());
413 | }
414 | // Añadir comando SET con TTL al pipeline
415 | $redis->set($chunkKey, $serializedChunk, ['EX' => self::$CHUNK_TTL]);
416 | }
417 |
418 | // Actualizar el índice con las llaves de los chunks
419 | // $resultIndex['Llaves'] = $llaves;
420 | // $resultIndex['InsertStatus'] = true; // Si llegamos aquí, la inserción se considera exitosa
421 | $resultIndex->Llaves = $llaves;
422 | $resultIndex->InsertStatus = true; // Si llegamos aquí, la inserción se considera exitosa
423 |
424 | $serializedIndex = json_encode($resultIndex);
425 | if ($serializedIndex === false) {
426 | $redis->discard();
427 | throw new Exception("Error al serializar el índice de resultados para Redis: " . json_last_error_msg());
428 | }
429 | // Añadir comando SET para el índice al pipeline
430 | $redis->set($idResultIndex, $serializedIndex, ['EX' => self::$CHUNK_TTL]);
431 |
432 | // Ejecutar todos los comandos en el pipeline
433 | // Las respuestas individuales de SET (true/false) no se chequean aquí
434 | // para mantener el pipeline simple. Si se necesita validación de cada SET,
435 | // se pueden revisar las respuestas del exec.
436 | $redis->exec();
437 |
438 | // Opcional: Si self::$lastResultId todavía se usa y es seguro en este contexto
439 | // self::$lastResultId = $resultsId;
440 |
441 | } catch (Exception $e) {
442 | // El pipeline se descarta automáticamente en caso de excepción en multi/exec.
443 | // Si quieres asegurarte de que ningún dato parcial quede, podrías intentar borrar llaves aquí,
444 | // pero si usas MULTI/EXEC, es "todo o nada".
445 | // Para errores de serialización, el discard ya fue llamado.
446 | throw new Exception("Fallo en la operación de inyección de resultados a Redis: " . $e->getMessage(), 0, $e);
447 | }
448 |
449 | // 4. Construir y devolver el objeto PageDefinition
450 | // El InsertStatus reflejará el éxito o fracaso capturado por la excepción
451 | // (si la excepción se lanza, esta parte del código no se ejecuta).
452 | // Si no hay excepción, InsertStatus será true.
453 | // $pageDef = new PageDefinition(
454 | // ResultsId: $resultIndex["ResultsId"], // Usar la clave correcta del array asociativo
455 | // InsertStatus: true, // Si llegamos aquí, la operación fue exitosa
456 | // RecordCount: $resultIndex["RecordCount"],
457 | // ChunkSize: $resultIndex["ChunkSize"],
458 | // ChunkLength: $resultIndex["ChunkLength"],
459 | // ChunkTtl: $resultIndex["ChunkTtl"],
460 | // ChunkTtlRefresh: $resultIndex["ChunkTtlRefresh"],
461 | // Llaves: $resultIndex["Llaves"],
462 | // );
463 |
464 | // return $pageDef;
465 | return $resultIndex;
466 | }
467 |
468 | public static function GetChunk($chunkKey) {
469 |
470 | // 1. Obtener la instancia de Redis
471 | try {
472 | $redis = RedisSvc::Init();
473 | } catch (Throwable $e) { // Captura cualquier excepción de conexión de RedisSvc::Init()
474 | throw new Exception("Error al conectar a Redis para GetResults: " . $e->getMessage(), 0, $e);
475 | }
476 |
477 | // 2. Obtener el chunk
478 | $serializedChunk = $redis->get($chunkKey);
479 |
480 | if ($serializedChunk === false) {
481 | // Si un chunk no se encuentra, es un problema.
482 | // Podría ser por expiración prematura, o una inconsistencia.
483 | throw new Exception("Chunk de resultados '$chunkKey' no encontrado o expirado. El conjunto de resultados podría estar incompleto.");
484 | }
485 |
486 | $chunkData = json_decode($serializedChunk, true);
487 |
488 | if (json_last_error() !== JSON_ERROR_NONE) {
489 | throw new Exception("Error al deserializar chunk de resultados '$chunkKey': " . json_last_error_msg());
490 | }
491 |
492 | return $chunkData;
493 | }
494 |
495 | public static function OrderBy(string $resultsId, string $orderField, $columns) {
496 |
497 | $topeRAM = 2048;
498 |
499 | if (!isset($orderField) || !isset($orderField['column'])) {
500 | return;
501 | }
502 | else {
503 | }
504 |
505 | try {
506 | // Primero obtener el indice
507 | //
508 | $index = self::GetIndex($resultsId);
509 |
510 | // Obtener una llave para calcular el tamaño de cada registro
511 | //
512 | $llaves = $index->Llaves;
513 | $llave = $llaves[0];
514 |
515 | if (!$index instanceof PageDefinition) {
516 | return;
517 | }
518 |
519 | // Obtener el chunk
520 | //
521 | $chunk = self::GetChunk($llave);
522 |
523 | if (is_array($chunk) && isset($chunk[0])) {
524 | $item = $chunk[0];
525 | }
526 | else {
527 | return;
528 | }
529 |
530 | // Calcular la cantidad de RAM utilizada por el objeto
531 | // (aproximado)
532 | $serializedItem = serialize($item);
533 | $sizeOfSerializedItem = strlen($serializedItem);
534 |
535 | // Dar un poco de holgura porque el método no es exacto
536 | // y no contempla el overhead de PHP con los objetos
537 | $sizeOfSerializedItemBytes = $sizeOfSerializedItem * 1.1;
538 |
539 | // Calcular para el total de registros
540 | $dataSizeMb = ($sizeOfSerializedItemBytes * $index->RecordCount) / (1024 * 1024);
541 |
542 | // Reservar memoria suficiente para los datos
543 | //
544 | $memFree = MemoryInfo::Instance()->AvailableMBCalculated;
545 |
546 | // Debemos reservar al menos 512MB para el sistema operativo
547 | //
548 | $dif = $memFree - $dataSizeMb;
549 |
550 | if ($dif < 512 || $dataSizeMb > $topeRAM) {
551 | throw new Exception('El ordenamiento no es posible debido a restricciones de tamaño del set de datos');
552 | }
553 |
554 | // Reservar la RAM
555 | //
556 | if ($dataSizeMb > 100) {
557 | $newSize = $dataSizeMb + 30;
558 | Ini::Instance()->Change(IniEnum::MEMORY_LIMIT, $newSize);
559 | }
560 |
561 | // Primero obtener TODOS los elementos
562 | //
563 | $resultado = self::GetResults($resultsId, -1);
564 |
565 | // Reordenar
566 | //
567 | $elementos = new GenericCollection(
568 | DtoName: $index->DtoName,
569 | Values: $resultado
570 | );
571 |
572 | //$elementos->OrderBy($column, $orderField[1]);
573 | }
574 | catch (Throwable $ex) {
575 | return;
576 | }
577 |
578 | }
579 |
580 |
581 | /**
582 | * Inserta un arreglo (chunk) en Redis con un TTL.
583 | *
584 | * @param string $chunkId La llave única para este chunk.
585 | * @param array $chunk El arreglo de datos a almacenar.
586 | * @return bool True si la operación fue exitosa, false en caso contrario.
587 | */
588 | private static function SaveChunk(string $chunkId, array $chunk)
589 | {
590 | // Serializa el arreglo a una cadena JSON antes de guardarlo en Redis
591 | $serializedChunk = json_encode($chunk);
592 |
593 | if ($serializedChunk === false) {
594 | throw new Exception("La información no se ha podido serializar");
595 | }
596 |
597 | $redis = RedisSvc::Init();
598 |
599 | // Si tenemos redis, actualizamos el valor de la coleccion
600 | if (isset($redis)) {
601 |
602 | // Inserta la llave con el valor serializado y el TTL
603 | // El método set de phpredis permite pasar un array de opciones
604 | // 'EX' para especificar el TTL en segundos
605 | $success = $redis->set($chunkId, $serializedChunk, ['EX' => self::$CHUNK_TTL]);
606 |
607 | if (!$success) {
608 | throw new Exception("No se ha podido ingresar la información a REDIS");
609 | }
610 | }
611 | else {
612 | throw new Exception("No se ha podido instanciar REDIS");
613 | }
614 | }
615 | }
--------------------------------------------------------------------------------
Total de líneas: 615
================================================================================
================================================================================
ARCHIVO #50: src/Cache/PageDefinition.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Cache/PageDefinition.php
Tamaño: 1.49 KB
--------------------------------------------------------------------------------
1 | ResultsId,
36 | DtoName : $index->DtoName,
37 | Key : $index->Key,
38 | OrderColumn : $index->OrderColumn,
39 | OrderDir : $index->OrderDir,
40 | InsertStatus : $index->InsertStatus,
41 | RecordCount : $index->RecordCount,
42 | ChunkSize : $index->ChunkSize,
43 | ChunkLength : $index->ChunkLength,
44 | ChunkTtl : $index->ChunkTtl,
45 | ChunkTtlRefresh : $index->ChunkTtlRefresh,
46 | Llaves : $index->Llaves,
47 | );
48 |
49 | }
50 |
51 | }
--------------------------------------------------------------------------------
Total de líneas: 51
================================================================================
================================================================================
ARCHIVO #51: src/Cache/PageResults.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Cache/PageResults.php
Tamaño: 475 bytes
--------------------------------------------------------------------------------
1 | connect($redisConfig->Endpoint, $redisConfig->Port);
28 | $redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP);
29 |
30 | // Probar la conexion
31 | if (self::Test($redis))
32 | return $redis;
33 | else
34 | return null;
35 | }
36 |
37 | static public function Test($redis) {
38 | return ($redis->ping() == "+PONG");
39 | }
40 |
41 | public static function FlushAll($includeSessions = false) {
42 |
43 | $redis = RedisSvc::Init();
44 |
45 | if (isset($redis)) {
46 |
47 | $allKeys = $redis->keys('*');
48 |
49 | foreach($allKeys as $key) {
50 | $encontrada = strpos($key, 'PHPREDIS_SESSION');
51 | if ($encontrada === false) {
52 | $redis->unlink($key);
53 | }
54 | }
55 | }
56 |
57 | }
58 |
59 | }
--------------------------------------------------------------------------------
Total de líneas: 59
================================================================================
================================================================================
ARCHIVO #53: src/Collection/AttachDefinition.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Collection/AttachDefinition.php
Tamaño: 537 bytes
--------------------------------------------------------------------------------
1 | $fieldX ?? '';
37 | $valueY = $item->$fieldY ?? '';
38 |
39 | $valuesX[$valueX] = true;
40 | $valuesY[$valueY] = true;
41 |
42 | // Mantener la clave con pipe ya que es segura
43 | $key = $valueX . '|' . $valueY;
44 | if (!isset($groupedData[$key])) {
45 | $groupedData[$key] = [];
46 | }
47 | $groupedData[$key][] = $item;
48 | }
49 |
50 | // Paso 2: Pre-procesar nombres de campos Y
51 | $cleanedValuesY = [];
52 | foreach (array_keys($valuesY) as $valueY) {
53 | $cleanedValuesY[$valueY] = self::CleanPropertyName($valueY);
54 | }
55 |
56 | // Paso 3: Construir matriz
57 | $matrix = [];
58 |
59 | foreach (array_keys($valuesX) as $valueX) {
60 | $row = new stdClass();
61 | $row->$fieldX = $valueX;
62 | $total = 0;
63 |
64 | foreach (array_keys($valuesY) as $valueY) {
65 | $cleanedFieldY = $cleanedValuesY[$valueY];
66 | $key = $valueX . '|' . $valueY;
67 |
68 | if (isset($groupedData[$key])) {
69 | // Optimización: array_sum con array_map
70 | $result = array_sum(array_map($function, $groupedData[$key]));
71 | $row->$cleanedFieldY = $result;
72 | $total += $result;
73 | } else {
74 | $row->$cleanedFieldY = null;
75 | }
76 | }
77 |
78 | $row->Total_Item = $total;
79 | $matrix[] = $row;
80 | }
81 |
82 | return $matrix;
83 | }
84 |
85 |
86 | public static function GetMatrixOld($data, string $fieldX, string $fieldY, callable $function): array
87 | {
88 | // Paso 1: Obtener todos los valores únicos para X e Y
89 | $valuesX = [];
90 | $valuesY = [];
91 | $groupedData = [];
92 |
93 | // Recorrer la colección para extraer valores únicos y agrupar datos
94 | foreach ($data as $item) {
95 | $valueX = $item->$fieldX ?? '';
96 | $valueY = $item->$fieldY ?? '';
97 |
98 | // Almacenar valores únicos para X e Y
99 | if (!in_array($valueX, $valuesX)) {
100 | $valuesX[] = $valueX;
101 | }
102 | if (!in_array($valueY, $valuesY)) {
103 | $valuesY[] = $valueY;
104 | }
105 |
106 | // Agrupar datos por combinación X,Y
107 | $key = $valueX . '|' . $valueY;
108 | if (!isset($groupedData[$key])) {
109 | $groupedData[$key] = [];
110 | }
111 | $groupedData[$key][] = $item;
112 | }
113 |
114 | // Paso 2: Limpiar nombres de campos Y para usarlos como propiedades
115 | $cleanedValuesY = [];
116 | foreach ($valuesY as $valueY) {
117 | $cleanedValuesY[$valueY] = self::CleanPropertyName($valueY);
118 | }
119 |
120 | // Paso 3: Crear la matriz resultado
121 | $matrix = [];
122 |
123 | foreach ($valuesX as $valueX) {
124 | // Crear objeto dinámico para esta fila
125 | $row = new stdClass();
126 | $row->$fieldX = $valueX;
127 |
128 | $row->Total_Item = 0;
129 |
130 | // Agregar columnas para cada valor Y
131 | $total = 0;
132 | foreach ($valuesY as $valueY) {
133 | $cleanedFieldY = $cleanedValuesY[$valueY];
134 | $key = $valueX . '|' . $valueY;
135 |
136 | if (isset($groupedData[$key])) {
137 | // Aplicar la función a todos los elementos de esta combinación
138 | $result = 0;
139 | foreach ($groupedData[$key] as $element) {
140 | $result += $function($element);
141 | }
142 | $row->$cleanedFieldY = $result;
143 | $total += $result;
144 | } else {
145 | // No hay datos para esta combinación
146 | $row->$cleanedFieldY = null;
147 | }
148 | }
149 |
150 | $row->Total_Item = $total;
151 | $matrix[] = $row;
152 | }
153 |
154 | return $matrix;
155 | }
156 |
157 | /**
158 | * Limpia el nombre de una propiedad para que sea válido en PHP
159 | * Reemplaza caracteres especiales y espacios
160 | *
161 | * @param string $name Nombre original
162 | * @return string Nombre limpio
163 | */
164 | private static function CleanPropertyName(string $name): string
165 | {
166 | // Reemplazar caracteres problemáticos
167 | $cleaned = str_replace(['/', '-', ' ', '.', ':', ';', ','], '_', $name);
168 |
169 | // Remover caracteres especiales adicionales
170 | $cleaned = preg_replace('/[^a-zA-Z0-9_]/', '_', $cleaned);
171 |
172 | // Remover múltiples guiones bajos consecutivos
173 | $cleaned = preg_replace('/_+/', '_', $cleaned);
174 |
175 | // Remover guiones bajos al inicio y final
176 | $cleaned = trim($cleaned, '_');
177 |
178 | // Si queda vacío o empieza con número, agregar prefijo
179 | if (empty($cleaned) || is_numeric($cleaned[0])) {
180 | $cleaned = 'field_' . $cleaned;
181 | }
182 |
183 | return $cleaned;
184 | }
185 |
186 | /**
187 | * Crea una tabla jerárquica donde las filas se agrupan por jerarquía y las columnas por un campo específico
188 | *
189 | * @param GenericCollection $data Colección de objetos que implementa Iterable
190 | * @param string $fieldX Campo para las columnas
191 | * @param callable $function Función que se aplicará a cada elemento para obtener el valor de la celda
192 | * @param string ...$fieldY Campos para la jerarquía de filas (del principal al detalle)
193 | * @return array Tabla jerárquica con totales por columnas
194 | */
195 | public static function GetTreeTable($data, string $fieldX, callable $function, string ...$fieldY): array
196 | {
197 | if (empty($fieldY)) {
198 | throw new InvalidArgumentException('Se requiere al menos un campo Y para construir la tabla');
199 | }
200 |
201 | // Obtener todos los valores únicos para las columnas (fieldX)
202 | $columnValues = [];
203 | foreach ($data as $item) {
204 | $colValue = $item->$fieldX ?? '';
205 | if (!in_array($colValue, $columnValues)) {
206 | $columnValues[] = $colValue;
207 | }
208 | }
209 |
210 | // Limpiar nombres de columnas
211 | $cleanedColumns = [];
212 | foreach ($columnValues as $colValue) {
213 | $cleanedColumns[$colValue] = self::CleanPropertyName($colValue);
214 | }
215 |
216 | // Construir la tabla jerárquica
217 | return self::BuildTreeTableLevel($data, $fieldY, 0, $fieldX, $cleanedColumns, $function, $campoTotal);
218 | }
219 |
220 | /**
221 | * Construye recursivamente un nivel de la tabla jerárquica
222 | */
223 | private static function BuildTreeTableLevel($data, array $hierarchyFields, int $level, string $columnField, array $cleanedColumns, callable $function): array
224 | {
225 | $currentField = $hierarchyFields[$level];
226 |
227 | // Agrupar datos por el campo actual
228 | $grouped = [];
229 | foreach ($data as $item) {
230 | $key = $item->$currentField ?? '';
231 | if (!isset($grouped[$key])) {
232 | $grouped[$key] = [];
233 | }
234 | $grouped[$key][] = $item;
235 | }
236 |
237 | $result = [];
238 |
239 | foreach ($grouped as $key => $items) {
240 | // Crear fila principal para este grupo
241 | $row = self::CreateTreeTableRow($key, $items, $columnField, $cleanedColumns, $level, $function);
242 | $result[] = (object)$row;
243 |
244 | // Si hay más niveles de jerarquía, crear sub-filas
245 | if ($level + 1 < count($hierarchyFields)) {
246 | $subRows = self::BuildTreeTableLevel($items, $hierarchyFields, $level + 1, $columnField, $cleanedColumns, $function);
247 | $result = array_merge($result, $subRows);
248 | }
249 | }
250 |
251 | return $result;
252 | }
253 |
254 | /**
255 | * Crea una fila de la tabla jerárquica con los totales por columna
256 | */
257 | private static function CreateTreeTableRow(string $item, array $items, string $columnField, array $cleanedColumns, int $level, callable $function): array
258 | {
259 | $row = [
260 | 'Item' => $item,
261 | 'Total_Item' => 0,
262 | 'Level' => $level
263 | ];
264 |
265 | // Agrupar items por valor de columna y aplicar la función
266 | $columnGroups = [];
267 |
268 | foreach ($items as $dataItem) {
269 | $colValue = $dataItem->$columnField ?? '';
270 | if (!isset($columnGroups[$colValue])) {
271 | $columnGroups[$colValue] = 0;
272 | }
273 | // Aplicar la función a cada elemento
274 | $columnGroups[$colValue] += $function($dataItem);
275 | }
276 |
277 | // Crear propiedades para cada columna
278 | $total = 0;
279 | foreach ($cleanedColumns as $originalValue => $cleanedName) {
280 | if (isset($columnGroups[$originalValue])) {
281 | $row[$cleanedName] = $columnGroups[$originalValue];
282 | } else {
283 | $row[$cleanedName] = 0;
284 | }
285 |
286 | $total += $row[$cleanedName];
287 | }
288 |
289 | $row['Total_Item'] = $total;
290 |
291 | return $row;
292 | }
293 |
294 |
295 | /**
296 | * Agrupa elementos iguales y cuenta las repeticiones
297 | *
298 | * @param GenericCollection $data Colección de objetos que implementa Iterable
299 | * @param string $countField Nombre del campo donde se almacenará el conteo
300 | * @param array $ignoredFields Campos que se ignoran para la comparación de igualdad
301 | * @return array Arreglo de objetos sin duplicados con el conteo en $countField
302 | */
303 | public static function GroupAndCount($data, string $countField, array $ignoredFields = []): array
304 | {
305 | $groups = [];
306 |
307 | foreach ($data as $item) {
308 | // Crear una clave única basada en los campos relevantes
309 | $key = self::CreateGroupKey($item, $ignoredFields);
310 |
311 | if (!isset($groups[$key])) {
312 | // Primer elemento de este grupo - clonar el objeto
313 | $groups[$key] = [
314 | 'item' => clone $item,
315 | 'count' => 1
316 | ];
317 | } else {
318 | // Incrementar el contador para este grupo
319 | $groups[$key]['count']++;
320 | }
321 | }
322 |
323 | // Preparar el resultado final
324 | $result = [];
325 | foreach ($groups as $group) {
326 | $resultItem = $group['item'];
327 | // Agregar la propiedad de conteo
328 | $resultItem->$countField = $group['count'];
329 | $result[] = $resultItem;
330 | }
331 |
332 | return $result;
333 | }
334 |
335 | /**
336 | * Crea una clave única para agrupar elementos basada en sus propiedades
337 | * excluyendo los campos ignorados
338 | *
339 | * @param object $item Elemento a procesar
340 | * @param array $ignoredFields Campos a ignorar en la comparación
341 | * @return string Clave única para el grupo
342 | */
343 | private static function CreateGroupKey($item, array $ignoredFields): string
344 | {
345 | $keyParts = [];
346 |
347 | // Obtener todas las propiedades públicas del objeto
348 | $properties = get_object_vars($item);
349 |
350 | // Ordenar las propiedades para consistencia
351 | ksort($properties);
352 |
353 | foreach ($properties as $property => $value) {
354 | // Saltar campos ignorados
355 | if (in_array($property, $ignoredFields)) {
356 | continue;
357 | }
358 |
359 | // Convertir el valor a string para la clave
360 | $stringValue = '';
361 | if ($value === null) {
362 | $stringValue = 'NULL';
363 | } elseif (is_bool($value)) {
364 | $stringValue = $value ? 'TRUE' : 'FALSE';
365 | } elseif (is_object($value)) {
366 | $stringValue = 'OBJECT_' . get_class($value);
367 | } elseif (is_array($value)) {
368 | $stringValue = 'ARRAY_' . json_encode($value);
369 | } else {
370 | $stringValue = (string) $value;
371 | }
372 |
373 | $keyParts[] = $property . ':' . $stringValue;
374 | }
375 |
376 | return md5(implode('|', $keyParts));
377 | }
378 | }
379 |
380 | // Ejemplo de uso:
381 | /*
382 | $result = Collections::GetMatrix(
383 | $data,
384 | 'Proveedor',
385 | 'FechaPicking',
386 | function($element) {
387 | if ($element->IdEstado == 1) return 1;
388 | else return 0;
389 | }
390 | );
391 |
392 | // El resultado sería un arreglo de objetos como:
393 | // [
394 | // {
395 | // "Proveedor": "Claudio",
396 | // "_10_09_2025": 1,
397 | // "_11_09_2025": 1,
398 | // "_13_09_2025": null
399 | // },
400 | // {
401 | // "Proveedor": "Juan",
402 | // "_10_09_2025": null,
403 | // "_11_09_2025": null,
404 | // "_13_09_2025": 1
405 | // }
406 | // ]
407 |
408 | // Para acceder a los datos:
409 | foreach ($result as $row) {
410 | echo "Proveedor: " . $row->Proveedor . "\n";
411 | foreach (get_object_vars($row) as $prop => $value) {
412 | if ($prop !== 'Proveedor' && $value !== null) {
413 | echo " $prop: $value\n";
414 | }
415 | }
416 | }
417 | */
418 |
419 | // Ejemplo de uso de GetTreeTable:
420 | /*
421 | $treeTableResult = Collections::GetTreeTable(
422 | $data,
423 | 'FechaPicking', // Campo X (columnas)
424 | function($element) {
425 | if ($element->IdEstado == 1) return 1;
426 | else return 0;
427 | }, // Función para evaluar cada elemento
428 | 'Proveedor', // Campo Y_1 (filas principales)
429 | 'Categoria' // Campo Y_2 (sub-filas)
430 | );
431 |
432 | // El resultado sería un arreglo como:
433 | // [
434 | // [
435 | // "Item" => "Claudio",
436 | // "Level" => 0,
437 | // "field_2025_09_10" => 3,
438 | // "field_2025_09_11" => 2,
439 | // "field_2025_09_13" => 0
440 | // ],
441 | // [
442 | // "Item" => "Categoria1",
443 | // "Level" => 1,
444 | // "field_2025_09_10" => 2,
445 | // "field_2025_09_11" => 2,
446 | // "field_2025_09_13" => 0
447 | // ],
448 | // [
449 | // "Item" => "Categoria2",
450 | // "Level" => 1,
451 | // "field_2025_09_10" => 1,
452 | // "field_2025_09_11" => 0,
453 | // "field_2025_09_13" => 0
454 | // ],
455 | // [
456 | // "Item" => "Juan",
457 | // "Level" => 0,
458 | // "field_2025_09_10" => 4,
459 | // "field_2025_09_11" => 0,
460 | // "field_2025_09_13" => 1
461 | // ],
462 | // [
463 | // "Item" => "Categoria1",
464 | // "Level" => 1,
465 | // "field_2025_09_10" => 0,
466 | // "field_2025_09_11" => 0,
467 | // "field_2025_09_13" => 1
468 | // ],
469 | // [
470 | // "Item" => "Categoria2",
471 | // "Level" => 1,
472 | // "field_2025_09_10" => 4,
473 | // "field_2025_09_11" => 0,
474 | // "field_2025_09_13" => 0
475 | // ]
476 | // ]
477 | */
--------------------------------------------------------------------------------
Total de líneas: 477
================================================================================
================================================================================
ARCHIVO #56: src/Collection/Condition.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Collection/Condition.php
Tamaño: 698 bytes
--------------------------------------------------------------------------------
1 | Entity;
40 | if (!isset($dtoName) || $dtoName == "") {
41 | throw new \Exception("La definición de entidad debe especificar el tipo de objeto contenido en -Entity-");
42 | }
43 |
44 | // Verificar que la definicion de entidad tenga definida la llave "Key"
45 | $key = $entityDefinition->KeyName;
46 | if (!isset($key) || $key == "") {
47 | throw new \Exception("La definicion de entidad debe especificar la llave principal en -KeyName-");
48 | }
49 |
50 | $this->ConditionsSentence = $conditions;
51 | $this->EntityDefinition = $entityDefinition;
52 |
53 | $this->Conditions = $this->PrepareConditions($conditions, $entityDefinition);
54 | }
55 |
56 | private function PrepareConditions($conditionsSentence, $entityDefinition) {
57 |
58 | // Analizar las condiciones y establecer parametros para la búsqueda en los índices
59 |
60 | // Separadores admitidos son:
61 | // &&
62 | // ||
63 | //
64 | // El separador && genera 2 condiciones
65 | // El separador || genera 2 subcondiciones dentro de 1 condicion
66 |
67 | // Separar las condiciones
68 | // ************************************************
69 |
70 | // Separador inicial &&
71 | $condicionesInicio = explode('&&', $conditionsSentence);
72 |
73 | $condicionesAnd = array();
74 | // Separador secundario ||
75 | foreach($condicionesInicio as $condicionInicio) {
76 | $condicionesOr = explode("||", $condicionInicio);
77 |
78 | foreach($condicionesOr as $or) {
79 | $cond = $this->BuildCondition($or, $entityDefinition);
80 | if (isset($cond)) {
81 | array_push($condicionesAnd, $cond);
82 | }
83 | }
84 | }
85 |
86 | return $condicionesAnd;
87 | }
88 |
89 | private function BuildCondition($condition, $entityDefinition) {
90 |
91 | // Construye una condición unitaria
92 | // **************************************
93 |
94 | // Obtener el operador
95 | // ***********************
96 | // Operadores admitidos son:
97 | // ==
98 | // >
99 | // >=
100 | // <
101 | // <=
102 | // !=
103 | $operadoresPosibles = ["==", ">", ">=", "<", "<=", "!="];
104 | $operador = "";
105 |
106 | foreach($operadoresPosibles as $op) {
107 | if (strpos($condition, $op)) {
108 | $operador = $op;
109 | break;
110 | }
111 | }
112 |
113 | // si no se encontró el operador, generar excepcion
114 | if ($operador == "")
115 | throw new \Exception("No se encontró del operador");
116 |
117 | // Procesar los operandos
118 | $parts = explode($operador, $condition);
119 |
120 | if (!isset($parts) || count($parts) != 2) {
121 | throw new \Exception("Condicion con error de sintaxis");
122 | }
123 |
124 | // Revisar el tipo de dato
125 | $fieldName = trim($parts[0]);
126 | $value = trim($parts[1]);
127 |
128 | if ($fieldName == "" || $value == "") {
129 | throw new \Exception("Condicion con error de sintaxis");
130 | }
131 |
132 | if (isset($entityDefinition)) {
133 | // Buscar el tipo de dato de la propiedad actual
134 | if (isset($entityDefinition->Properties[$fieldName])) {
135 | $plop = $entityDefinition->Properties[$fieldName];
136 | }
137 | }
138 |
139 | // Construir la condicion
140 | $condicion = new Condition([
141 | "FieldName" => $fieldName,
142 | "Operator" => $operador,
143 | "Value" => $value,
144 | "FieldType" => "unknown"
145 | ]);
146 |
147 | return $condicion;
148 | }
149 | }
--------------------------------------------------------------------------------
Total de líneas: 149
================================================================================
================================================================================
ARCHIVO #58: src/Collection/GenericCollection.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Collection/GenericCollection.php
Tamaño: 41.63 KB
--------------------------------------------------------------------------------
1 |
86 | */
87 |
88 | #[AllowDynamicProperties]
89 | class GenericCollection implements IteratorAggregate, JsonSerializable {
90 |
91 | public $Type = "Collection";
92 | public $DtoDefinition = null;
93 | public $Cache;
94 | protected $EntityDefinition;
95 |
96 | /**
97 | * @param array $definition
98 | *
99 | * Arreglo asociativo con los elementos necesarios para crear la coleccion
100 | *
101 | * Ej:
102 | *
103 | * ["Key" => "Id", "DtoName" => "myClass", "Values" => $miArreglo ]
104 | *
105 | */
106 | function __construct(
107 | protected $DtoName = '',
108 | protected $Key = '',
109 | public $Values = [],
110 | protected $Indexes = [],
111 | protected $ClassName = '',
112 | public $ReflectDto = false
113 | )
114 | {
115 | $this->Cache = new Cache();
116 |
117 | if (!isset($this->Values)) {
118 | $this->Values = [];
119 | }
120 |
121 | if ($this->DtoName == '' && $this->Key != '') {
122 | throw new \Exception("Debe especificar el DTO para usar una GenericCollection con designacion de KEY");
123 | }
124 |
125 | if (isset($this->Indexes) && count($this->Indexes) > 0 && $this->Key == '') {
126 | throw new \Exception("Debe especificar una llave -Key- cuando desea especificar índices secundarios");
127 | }
128 |
129 | if ($this->DtoName != '' && $this->ClassName == '') {
130 | $this->ClassName = $this->GetClassName($this->DtoName);
131 | }
132 |
133 | $dtStartIndexMonitor = microtime(true);
134 | if ($this->Key != '' && isset($this->Values)) {
135 | $this->CreatePrimaryIndex($this->Key);
136 | }
137 |
138 | if (isset($this->Indexes) && count($this->Indexes) > 0) {
139 | $this->CreateSecondaryIndexes($this->Indexes);
140 | }
141 | $dtEndIndexMonitor = microtime(true);
142 |
143 | // Obtener las propiedades reflectadas de la coleccion
144 | if ($this->DtoName != '' && $this->ReflectDto) {
145 | $this->EntityDefinition = EntityDefinition::Instance($this->DtoName);
146 | }
147 |
148 | Monitor::$KeyIndexExecutions++;
149 | Monitor::$KeyIndexExecutionTime += ($dtEndIndexMonitor - $dtStartIndexMonitor);
150 | }
151 |
152 | public function __clone() {
153 | // Obtenemos una copia de los valores
154 | $clonedValues = array();
155 |
156 | foreach($this->Values as $val) {
157 |
158 | $clonedItem = new $this->DtoName();
159 | // recorrer los valores
160 | foreach($val as $propname => $propvalue) {
161 | $clonedItem->$propname = $propvalue;
162 | }
163 | array_push($clonedValues, $clonedItem);
164 | }
165 |
166 | $this->Key = $this->Key;
167 | $this->DtoName = $this->DtoName;
168 | $this->Values = $clonedValues;
169 | }
170 |
171 | public function jsonSerialize(): mixed {
172 |
173 | return $this->Values;
174 |
175 | }
176 |
177 | public function getIterator() : Traversable {
178 | return new ArrayIterator($this->Values);
179 | }
180 |
181 | public function CreateIndex(array $values, $key, $secondaryKey = "") {
182 |
183 | $outputArray = array();
184 |
185 | foreach($values as $idx => $value) {
186 |
187 | // Convertir el valor de la llave en un número para acelerar las búsquedas, de ser posible
188 | if (is_numeric($value->$key)) {
189 | $valKey = $value->$key * 1;
190 | }
191 | else {
192 | $valKey = $value->$key;
193 | }
194 |
195 | if ($secondaryKey == "") {
196 | // Si es sólo la llave principal, indexamos en el indice principal
197 | // el indice del arreglo asociado a dicha llave
198 | $outputArray[$valKey] = $idx;
199 | }
200 | else {
201 | // Si es un índice secundario, sólo indexamos el valor
202 | // de la llave principal como un subarreglo dentro
203 | // del índice asociado a la llave secundaria
204 | //
205 | // arr['idsecundario'] = [ 'key1', 'key2', 'key3', ... , 'keyN']
206 | //
207 | // Convertir el valor de la llave secundaria en un número para acelerar las búsquedas
208 |
209 | // obtener el valor multinivel en caso de existir
210 | $valueMultilevel = Mapper::EvaluateKeyMultilevel($value, $secondaryKey); // $this->GetMultiLevelKeyValue($value, $secondaryKey);
211 |
212 | if (is_numeric($valueMultilevel)) {
213 | $secKey = $valueMultilevel * 1;
214 | }
215 | else {
216 | $secKey = $valueMultilevel;
217 | }
218 |
219 | if ( !isset( $outputArray[$secKey] ) ) {
220 | $outputArray[$secKey] = array();
221 | }
222 |
223 | // Agregar la llave principal como subitem (sólo si no existe)
224 | if (!isset( $outputArray[ $secKey ] [ $valKey ] )) {
225 | // asociamos el IDX del arreglo original en el indice secundario
226 | $outputArray[$secKey][$valKey] = $idx;
227 | }
228 | }
229 | }
230 |
231 | // Para acelerar las búsquedas, debemos ordenar el arreglo por su llave
232 | ksort($outputArray);
233 |
234 | return $outputArray;
235 | }
236 |
237 | private function CreatePrimaryIndex(string $key) {
238 | $this->GetLocalCache()->PrimaryIndex = $this->CreateIndex($this->Values, $key);
239 | }
240 |
241 | private function CreateSecondaryIndexes(array $indices) {
242 |
243 | foreach($indices as $indice) {
244 | // Generar un índice secundario
245 | if (!isset($this->GetLocalCache()->SecondaryIndexes[$indice])) {
246 | $this->GetLocalCache()->SecondaryIndexes[$indice] = $this->CreateIndex($this->Values, $this->Key, $indice);
247 | }
248 | }
249 |
250 | }
251 |
252 | public function Reindex() {
253 | // Regenerar el indice principal
254 | if ($this->Key != "")
255 | $this->GetLocalCache()->PrimaryIndex = $this->CreateIndex($this->Values, $this->Key);
256 |
257 | // Regenerar los indices secundarios
258 | foreach($this->GetLocalCache()->SecondaryIndexes as $key => $indice) {
259 | $this->GetLocalCache()->SecondaryIndexes[$key] = $this->CreateIndex($this->Values, $this->Key, $key);
260 | }
261 | }
262 |
263 | /**
264 | * Ordena la colección según las propiedades del objeto
265 | *
266 | * @param string $fields
267 | * Especifica las propiedades y el orden en el que se realizará el ordenamiento.
268 | * Admite el uso de ASC y DESC.
269 | *
270 | * Si no es especifica, el valor por defecto del orden de cada campo será ASC.
271 | *
272 | * Ej:
273 | *
274 | * $mycollection->OrderBy("FechaRegistro DESC, IdComuna");
275 | *
276 | * @author Claudio Gonzalez
277 | * @return void
278 | */
279 | public function OrderBy($fields) {
280 |
281 | $orders = explode(",", trim($fields));
282 |
283 | $arrOrders = array();
284 | foreach($orders as $order) {
285 | $parts = explode(' ', trim($order));
286 | $order = new \StdClass();
287 | $order->Fieldname = $parts[0];
288 |
289 | if (count($parts) == 1 || ( count($parts) == 2 && strtolower(trim($parts[1])) != "desc" )) {
290 | $order->Direction = "ASC";
291 | }
292 | else if ( count($parts) == 2 && strtolower(trim($parts[1])) == "desc" ) {
293 | $order->Direction = "DESC";
294 | }
295 |
296 | $arrOrders[$parts[0]] = $order;
297 | }
298 |
299 | // Ordenar el arreglo
300 | usort($this->Values, function($a, $b) use($arrOrders) {
301 |
302 | // Comparar los valores en el orden para ir viendo el orden
303 | foreach($arrOrders as $order) {
304 | $fieldName = $order->Fieldname;
305 | $campoSource = $a->$fieldName;
306 | $campoCompare = $b->$fieldName;
307 | $direction = $order->Direction;
308 |
309 | if ($direction == "ASC") {
310 | // Si a es mayor, va primero
311 | if ($campoSource != $campoCompare) {
312 | return ($campoSource > $campoCompare) ? 1 : -1;
313 | }
314 | }
315 | else {
316 | // Si a es menor, va primero
317 | return ($campoSource < $campoCompare) ? 1 : -1;
318 | }
319 | }
320 |
321 | // No se encontraron diferencias
322 | return 0;
323 | });
324 |
325 | // Reindexar
326 | $this->Reindex();
327 | }
328 |
329 | public function Top(int $rows) : GenericCollection {
330 |
331 | if ($rows > 350) {
332 | $rows = 350;
333 | }
334 |
335 | $result = array_slice($this->Values, 0, $rows);
336 |
337 | return new GenericCollection(
338 | DtoName: $this->DtoName,
339 | Key: $this->Key,
340 | Values: $result
341 | );
342 | }
343 |
344 | public function Tail(int $rows) : GenericCollection {
345 |
346 | if ($rows > 350) {
347 | $rows = 350;
348 | }
349 |
350 | $count = count($this->Values);
351 | $offset = max(0, $count - $rows);
352 |
353 | $result = array_slice($this->Values, $offset, $rows);
354 |
355 | return new GenericCollection(
356 | DtoName: $this->DtoName,
357 | Key: $this->Key,
358 | Values: $result
359 | );
360 | }
361 |
362 | /**
363 | * Crea una copia de la colección, ordenada según las propiedades del objeto
364 | *
365 | * @param string $fields
366 | * Especifica las propiedades y el orden en el que se realizará el ordenamiento.
367 | * Admite el uso de ASC y DESC.
368 | *
369 | * Si no es especifica, el valor por defecto del orden de cada campo será ASC.
370 | *
371 | * Ej:
372 | *
373 | * $newCollection = $mycollection->OrderedBy("FechaRegistro DESC, IdComuna");
374 | *
375 | *
376 | * @author Claudio Gonzalez
377 | * @return GenericCollection
378 | */
379 | public function OrderedBy($fields) {
380 |
381 | // Revisar caché
382 | if ($fields != $this->GetLocalCache()->LastOrderedByCondition) {
383 |
384 | // Actualizar caché
385 | $this->GetLocalCache()->LastOrderedByCondition = $fields;
386 |
387 | $clone = null;
388 |
389 | $orders = explode(",", trim($fields));
390 |
391 | $arrOrders = array();
392 | foreach($orders as $order) {
393 | $parts = explode(' ', trim($order));
394 | $order = new \StdClass();
395 | $order->Fieldname = $parts[0];
396 |
397 | if (count($parts) == 1 || ( count($parts) == 2 && strtolower(trim($parts[1])) != "desc" )) {
398 | $order->Direction = "ASC";
399 | }
400 | else if ( count($parts) == 2 && strtolower(trim($parts[1])) == "desc" ) {
401 | $order->Direction = "DESC";
402 | }
403 |
404 | $arrOrders[$parts[0]] = $order;
405 | }
406 |
407 | // Clonamos los valores de la colección para no afectar los valores originales, los cuales
408 | // mantienen su orden inicial.
409 | $clone = clone $this;
410 |
411 | // Ordenar el arreglo
412 | usort($clone->Values, function($a, $b) use($arrOrders) {
413 |
414 | // Comparar los valores en el orden para ir viendo el orden
415 | foreach($arrOrders as $order) {
416 | $fieldName = $order->Fieldname;
417 | $campoSource = $a->$fieldName;
418 | $campoCompare = $b->$fieldName;
419 | $direction = $order->Direction;
420 |
421 | if ($direction == "ASC") {
422 | // Si a es mayor, va primero
423 | if ($campoSource != $campoCompare) {
424 | return ($campoSource > $campoCompare) ? 1 : -1;
425 | }
426 | }
427 | else {
428 | // Si a es menor, va primero
429 | return ($campoSource < $campoCompare) ? 1 : -1;
430 | }
431 | }
432 |
433 | // No se encontraron diferencias
434 | return 0;
435 | });
436 |
437 | // Actualizar caché
438 | $this->GetLocalCache()->LastOrderedBy = $clone;
439 | }
440 |
441 | return $this->GetLocalCache()->LastOrderedBy;
442 | }
443 |
444 | /**
445 | * Encuentra el primer elemento de la colección según el orden actual
446 | *
447 | *
448 | * @author Claudio Gonzalez
449 | * @return object
450 | */
451 | public function First() {
452 |
453 | if (count($this->Values) <= 0) {
454 | return null;
455 | }
456 | else {
457 | return reset($this->Values);
458 | }
459 |
460 | }
461 |
462 | public function Last() {
463 |
464 | if (count($this->Values) <= 0) {
465 | return null;
466 | }
467 | else {
468 | return end($this->Values);
469 | }
470 |
471 | }
472 |
473 | public function Count() {
474 |
475 | if ($this->GetLocalCache()->LastCount < 0) {
476 | // Actualizar caché
477 | $this->GetLocalCache()->LastCount = count($this->Values);
478 | }
479 |
480 | return $this->GetLocalCache()->LastCount;
481 | }
482 |
483 | private function RemoveItem($item) {
484 | $pos = -1;
485 |
486 | for ($i = 0; $i < count($this->Values); $i++) {
487 | if ($this->Values[$i] == $item) {
488 | $pos = $i;
489 | break;
490 | }
491 | }
492 |
493 | if ($pos >= 0) {
494 | \array_splice($this->Values, $pos, 1);
495 | }
496 | }
497 |
498 | public function Remove($item, $reIndex = true) {
499 |
500 | $this->RemoveItem($item);
501 |
502 | // Invalidar la caché
503 | $this->InvalidarCache();
504 |
505 | // Reindexar
506 | if ($reIndex)
507 | $this->Reindex();
508 | }
509 |
510 | public function RemoveWhere($condicion, $reIndex = true) {
511 |
512 | $condicion = $this->SingleEqualSignReplace($condicion);
513 |
514 | // Buscar variables dentro de la condicion
515 | $pivote = get_class_vars($this->DtoName); // new $this->DtoName();
516 |
517 | foreach($pivote as $propname => $propvalue) {
518 | $condicion = $this->TokenReplace($propname, "\$value->" . $propname, $condicion);
519 | }
520 |
521 | // Clonamos el arreglo
522 | $clone = clone $this;
523 | $deletedValues = array();
524 |
525 | $idx= 0;
526 | foreach($clone->Values as $value) {
527 | $resultado = eval('return (' . $condicion . ');');
528 |
529 | if ($resultado) {
530 | $deletedValues[$idx] = $value;
531 | $idx++;
532 | }
533 | }
534 |
535 | // Borrar los elementos encontrados
536 | foreach($deletedValues as $delete) {
537 | $this->RemoveItem($delete);
538 | }
539 |
540 | $this->InvalidarCache();
541 | // Reindexar
542 | if ($reIndex)
543 | $this->Reindex();
544 | }
545 |
546 | private function AddItem($item, $first = false) {
547 |
548 | if ($first) {
549 | array_unshift($this->Values, $item);
550 | }
551 | else {
552 | array_push($this->Values, $item);
553 | }
554 | }
555 |
556 | public function Add($item, $reIndex = true, $first = false) {
557 |
558 | $this->AddItem($item, $first);
559 | $this->InvalidarCache();
560 |
561 | // Reindexar
562 | if ($reIndex)
563 | $this->Reindex();
564 |
565 | return $this;
566 | }
567 |
568 | public function AddRange($items, $reIndex = true) {
569 |
570 | foreach($items as $item) {
571 | $this->AddItem($item);
572 | }
573 |
574 | $this->InvalidarCache();
575 | // Reindexar
576 | if ($reIndex)
577 | $this->Reindex();
578 |
579 | return $this;
580 | }
581 |
582 | private function InvalidarCache() {
583 | $this->GetLocalCache()->LastOrderedBy = array();
584 | $this->GetLocalCache()->LastOrderedByCondition = "";
585 | $this->GetLocalCache()->LastWhere = array();
586 | $this->GetLocalCache()->LastWhereCondition = "";
587 | $this->GetLocalCache()->LastFirstWhere = null;
588 | $this->GetLocalCache()->LastFirstWhereCondition = "";
589 | $this->GetLocalCache()->LastAvg = 0;
590 | $this->GetLocalCache()->LastAvgField = "";
591 | $this->GetLocalCache()->LastSum = 0;
592 | $this->GetLocalCache()->LastSumField = "";
593 | $this->GetLocalCache()->LastMax = 0;
594 | $this->GetLocalCache()->LastMaxField = "";
595 | $this->GetLocalCache()->LastMin = 0;
596 | $this->GetLocalCache()->LastMinField = "";
597 | $this->GetLocalCache()->LastItemMax = null;
598 | $this->GetLocalCache()->LastItemMaxField = "";
599 | $this->GetLocalCache()->LastMinItem = null;
600 | $this->GetLocalCache()->LastMinItemField = "";
601 | $this->GetLocalCache()->LastCount = -1;
602 | $this->GetLocalCache()->LastDistinctField = "";
603 | $this->GetLocalCache()->LastDistinct = null;
604 | $this->GetLocalCache()->LastDistinctItemField = "";
605 | $this->GetLocalCache()->LastDistinctItem = null;
606 | }
607 |
608 | public function Clear() {
609 | $this->Values = array();
610 |
611 | // Eliminar caché
612 | $this->InvalidarCache();
613 |
614 | // Reindexar
615 | $this->Reindex();
616 | }
617 |
618 | public function Where($condicion) {
619 |
620 | $condicion = $this->SingleEqualSignReplace($condicion);
621 |
622 | if ($this->GetLocalCache()->LastWhereCondition != $condicion) {
623 |
624 | $condicion = $this->SingleEqualSignReplace($condicion);
625 |
626 | // Actualizar caché
627 | $this->GetLocalCache()->LastWhereCondition = $condicion;
628 |
629 | // Buscar variables dentro de la condicion
630 | $pivote = get_class_vars($this->DtoName); // new $this->DtoName();
631 |
632 | foreach($pivote as $propname => $propvalue) {
633 | $condicion = $this->TokenReplace($propname, "\$value->" . $propname, $condicion);
634 | }
635 |
636 | $newValues = array();
637 |
638 | $idx= 0;
639 | // Los valores no se clonan, para que hereden cualquier modificacion
640 | // que se realice posterior a la llamada
641 | foreach($this->Values as $value) {
642 | $resultado = eval('return (' . $condicion . ');');
643 |
644 | if ($resultado) {
645 | $newValues[$idx] = $value;
646 | $idx++;
647 | }
648 | }
649 |
650 | // Actualizar caché
651 | $this->GetLocalCache()->LastWhere = new GenericCollection(
652 | Key: $this->Key,
653 | DtoName: $this->DtoName,
654 | Values: $newValues
655 | );
656 | }
657 |
658 | return $this->GetLocalCache()->LastWhere;
659 | }
660 |
661 | private function GetLocalCache() {
662 |
663 | if (!isset($this->Cache)) {
664 | $this->Cache = new Cache();
665 | }
666 |
667 | return $this->Cache;
668 | }
669 |
670 | public function FirstWhere($condicion) {
671 |
672 | $condicion = $this->SingleEqualSignReplace($condicion);
673 |
674 | $dtStartMonitor = microtime(true);
675 |
676 | if ($this->GetLocalCache()->LastFirstWhereCondition != $condicion) {
677 |
678 | $found = null;
679 |
680 | // Actualizar caché
681 | $this->GetLocalCache()->LastFirstWhereCondition = $condicion;
682 |
683 | // Buscar variables dentro de la condicion
684 | $pivote = get_class_vars($this->DtoName); // new $this->DtoName();
685 |
686 | foreach($pivote as $propname => $propvalue) {
687 | $condicion = $this->TokenReplace($propname, "\$value->" . $propname, $condicion);
688 | }
689 |
690 | // Evitar la asignacion
691 | $condicion = str_replace(" = ", " == ", $condicion);
692 |
693 | $idx = 0;
694 | // precalcular para que no se calcule con cada ciclo for(;;)
695 | $cant = count($this->Values);
696 |
697 | // Recorremos en el orden del arreglo actual (no utilizaremos foreach)
698 | for($i = 0; $i < $cant; $i++) {
699 | $value = $this->Values[$i];
700 | $resultado = eval('return (' . $condicion . ');');
701 |
702 | if ($resultado) {
703 | // retornamos el primer resultado que encontremos
704 | $found = $value;
705 | break;
706 | }
707 | }
708 |
709 | // Actualizar caché (podría ser null inclusive)
710 | $this->GetLocalCache()->LastFirstWhere = $found;
711 | }
712 |
713 | $dtEndMonitor = microtime(true);
714 |
715 | Monitor::$FromTimeExecutions++;
716 | Monitor::$FromTimeExecutionTime += ($dtEndMonitor - $dtStartMonitor);
717 |
718 | return $this->GetLocalCache()->LastFirstWhere;
719 | }
720 |
721 | public function Find($primaryIndexKey) {
722 |
723 | // Para acelerar el proceso, debemos indexar por la llave primaria!!, si es que existe
724 | if (!isset($this->GetLocalCache()->PrimaryIndex) && $this->Key != "") {
725 | $this->CreatePrimaryIndex($this->Key);
726 | }
727 |
728 | if (isset($this->GetLocalCache()->PrimaryIndex[$primaryIndexKey])) {
729 | $indexKey = $this->GetLocalCache()->PrimaryIndex[$primaryIndexKey];
730 | return (isset($this->Values[$indexKey])) ? $this->Values[$indexKey] : null;
731 | }
732 | else {
733 | return null;
734 | }
735 |
736 | }
737 |
738 | public function Exists($primaryIndexKey) {
739 | // Para acelerar el proceso, debemos indexar por la llave primaria!!, si es que existe
740 | if (!isset($this->GetLocalCache()->PrimaryIndex) && $this->Key != "") {
741 | $this->CreatePrimaryIndex($this->Key);
742 | }
743 |
744 | return (isset($this->GetLocalCache()->PrimaryIndex[$primaryIndexKey]));
745 | }
746 |
747 | public function Attach(AttachDefinition $attachDefinition) {
748 |
749 | // Los valores deben ser una Coleccion basada en GenericCollection
750 | // el valor de $attachDefinition->Values, debe ser un objeto GenericCollection o una clase derivada
751 | if (!isset($attachDefinition->Values) || !($attachDefinition->Values instanceof GenericCollection))
752 | throw new \Exception("Debe especificar una coleccion basada en GenericCollection para atachar");
753 |
754 | if ($attachDefinition->AttachPrimaryKey != "") {
755 | $attachPrimaryKey = $attachDefinition->AttachPrimaryKey;
756 | }
757 | else if ($attachDefinition->Values->Key != "") {
758 | $attachPrimaryKey = $attachDefinition->Values->Key;
759 | }
760 | else if ( isset($attachDefinition->Values) && isset($attachDefinition->Values->EntityDefinition) && $attachDefinition->Values->EntityDefinition->KeyName != "") {
761 | $attachPrimaryKey = $attachDefinition->Values->EntityDefinition->KeyName;
762 | }
763 |
764 | // Foreign Key representa el campo del registro actual (al cual le atacharemos su PARENT row) que hace referencia a la primary key del PARENT
765 | $foreignKey = $attachDefinition->ForeignKey == "" ? $attachPrimaryKey : $attachDefinition->ForeignKey;
766 |
767 | $attachPropertyName = $attachDefinition->AttachPropertyName == "" ? $attachDefinition->Values->ClassName : $attachDefinition->AttachPropertyName;
768 | $values = $attachDefinition->Values;
769 |
770 | if ( $values->Count() <= 0)
771 | return;
772 |
773 | // Para acelerar las asignaciones, debemos crear un índice con la definición
774 | // de la entidad ATTACH
775 | if (!isset($this->GetLocalCache()->SecondaryIndexes[$foreignKey]) && $this->Key != "") {
776 | $this->CreateSecondaryIndexes([
777 | $foreignKey
778 | ]);
779 | }
780 |
781 | // Comenzar el bucle de busqueda por cada referencia
782 | foreach($values as $attach) {
783 |
784 | // Tenemos que incorporar los $values como una nueva propiedad en cada elemento cuyas llaves coincidan
785 |
786 | // Revisar si existe un índice secundario con este campo
787 | if (isset($this->GetLocalCache()->PrimaryIndex) && isset($this->GetLocalCache()->SecondaryIndexes) && count($this->GetLocalCache()->SecondaryIndexes) > 0 && isset($this->GetLocalCache()->SecondaryIndexes[$foreignKey])) {
788 | // Buscamos el elemento directo en el índice
789 | $idxSecondary = null;
790 |
791 | if (isset($this->GetLocalCache()->SecondaryIndexes[$foreignKey]) && isset($this->GetLocalCache()->SecondaryIndexes[$foreignKey] [$attach->$attachPrimaryKey]))
792 | $idxSecondary = $this->GetLocalCache()->SecondaryIndexes[$foreignKey] [$attach->$attachPrimaryKey];
793 |
794 | if (isset($idxSecondary)) {
795 | foreach($idxSecondary as $secondary) {
796 | $found = $this->Values[$secondary];
797 | $found->$attachPropertyName = $attach;
798 | }
799 | }
800 | }
801 | else {
802 | $condicion = $foreignKey . " == " . $attach->$attachPrimaryKey;
803 |
804 | if (isset($condicion)) {
805 | // Buscar el elemento que aplique a esta condicion de referencia
806 | $found = $this->Where($condicion);
807 |
808 | if (isset($found)) {
809 | foreach($found as $item) {
810 | $item->$attachPropertyName = $attach;
811 | }
812 | }
813 | }
814 | }
815 | }
816 | }
817 |
818 | public function MergeChildren(MergeDefinition $mergeDefinition) {
819 |
820 | $dtStartMonitor = microtime(true);
821 |
822 | // Para acelerar el proceso, debemos indexar por la llave primaria!!, si es que existe
823 | if (!isset($this->GetLocalCache()->PrimaryIndex) && $this->Key != "") {
824 | $this->CreatePrimaryIndex($this->Key);
825 | }
826 |
827 | // Los valores deben ser una Coleccion basada en GenericCollection
828 | if (!isset($mergeDefinition->Values) || !($mergeDefinition->Values instanceof GenericCollection))
829 | throw new \Exception("Debe especificar una coleccion basada en GenericCollection para realizar merge");
830 |
831 | $parentKey = $mergeDefinition->ParentKey == "" ? $this->Key : $mergeDefinition->ParentKey;
832 | $childReferenceKey = $mergeDefinition->ChildReferenceKey == "" ? $parentKey : $mergeDefinition->ChildReferenceKey;
833 | $parentCollectionName = $mergeDefinition->ParentCollectionName == "" ? $this->Pluralize($mergeDefinition->Values->ClassName) : $mergeDefinition->ParentCollectionName;
834 | $values = $mergeDefinition->Values;
835 |
836 | if (is_array($values) && count($values) <= 0)
837 | return;
838 | else if ( $values->Count() <= 0)
839 | return;
840 |
841 | // Almacenar resultados en un arreglo caché para acelerar
842 | // las búsquedas en grandes cantidades de elementos, cuando
843 | // el índice no existe
844 | $searchCache = array();
845 | $parentFound = null;
846 |
847 | // Comenzar el bucle de busqueda por cada child
848 | foreach($values as $child) {
849 | // Buscar el parent
850 | unset($parentFound);
851 |
852 | // SI EL ARREGLO ESTA INDEXADO usamos el indice
853 | if (isset($this->GetLocalCache()->PrimaryIndex) && count($this->GetLocalCache()->PrimaryIndex) > 0) {
854 | if (isset($this->GetLocalCache()->PrimaryIndex[$child->$childReferenceKey])) {
855 | $llaveBuscada = $this->GetLocalCache()->PrimaryIndex[$child->$childReferenceKey];
856 | if (isset($this->Values[$llaveBuscada]))
857 | $parentFound = $this->Values[$llaveBuscada];
858 | }
859 | }
860 |
861 | if (!isset($parentFound)) {
862 | // SI NO EXISTE INDICE, buscamos por condicion, utilizamos caché para almacenar búsquedas previas
863 | //else {
864 | $condicion = null;
865 |
866 | if (isset($child->$childReferenceKey)) {
867 | if (is_string($child->$childReferenceKey))
868 | $condicion = $parentKey . " == '" . $child->$childReferenceKey . "'";
869 | else
870 | $condicion = $parentKey . " == " . $child->$childReferenceKey;
871 | }
872 |
873 | if (isset($condicion)) {
874 | // Buscar el elemento padre que aplique a esta condicion de referencia
875 | // Buscar primero en caché
876 | if (isset($searchCache[$child->$childReferenceKey])) {
877 | $parentFound = $searchCache[$child->$childReferenceKey];
878 | }
879 | else {
880 | $parentFound = $this->FirstWhere($condicion);
881 | // Agregar al cache
882 | $searchCache[$child->$childReferenceKey] = $parentFound;
883 | }
884 | }
885 | }
886 |
887 | if (isset($parentFound)) {
888 | if (!isset($parentFound->$parentCollectionName))
889 | $parentFound->$parentCollectionName = [];
890 |
891 | array_push($parentFound->$parentCollectionName, $child);
892 | }
893 | }
894 |
895 | $dtEndMonitor = microtime(true);
896 |
897 | Monitor::$MergeChildrenExecutions++;
898 | Monitor::$MergeChildrenExecutionTime += ($dtEndMonitor - $dtStartMonitor);
899 | }
900 |
901 | private function GetClassName(string $dtoName) {
902 |
903 | $pos = strrpos($dtoName, '\\');
904 |
905 | if ($pos) {
906 | return str_replace('\\', '', substr($dtoName, $pos));
907 | }
908 | }
909 |
910 | private function Pluralize(string $definition) {
911 |
912 | $plural = "es";
913 |
914 | // Primero revisar el ultimo elemento
915 | $lastChar = strtolower(substr($definition, -1, 1));
916 |
917 | if ($lastChar == 'a' || $lastChar == 'e' || $lastChar == 'o') {
918 | $plural = "s";
919 | }
920 |
921 | return $definition . $plural;
922 | }
923 |
924 | public function Avg($field) {
925 |
926 | if ($this->GetLocalCache()->LastAvgField != $field) {
927 |
928 | // Actualizar caché
929 | $this->GetLocalCache()->LastAvgField = $field;
930 |
931 | if ($this->Count() <= 0)
932 | return 0;
933 |
934 | $sum = $this->Sum($field);
935 |
936 | // Actualizar caché
937 | $this->GetLocalCache()->LastAvg = ($sum / $this->Count());
938 | }
939 |
940 | return $this->GetLocalCache()->LastAvg;
941 | }
942 |
943 | public function Sum($field) {
944 |
945 | if ($this->GetLocalCache()->LastSumField != $field) {
946 | // Actualizar caché
947 | $this->GetLocalCache()->LastSumField = $field;
948 |
949 | $sum = 0;
950 |
951 | foreach($this->Values as $value) {
952 | $sum += $value->$field * 1;
953 | }
954 |
955 | // Actualizar caché
956 | $this->GetLocalCache()->LastSum = $sum;
957 | }
958 |
959 | return $this->GetLocalCache()->LastSum;
960 | }
961 |
962 | public function SumWhere($sumField, $condicion) {
963 |
964 | $sumResult = 0;
965 |
966 | $condicion = $this->SingleEqualSignReplace($condicion);
967 |
968 | // Buscar variables dentro de la condicion
969 | $pivote = get_class_vars($this->DtoName); // new $this->DtoName();
970 |
971 | foreach($pivote as $propname => $propvalue) {
972 | $condicion = $this->TokenReplace($propname, "\$value->" . $propname, $condicion);
973 | }
974 |
975 | // Evitar la asignacion
976 | $condicion = str_replace(" = ", " == ", $condicion);
977 |
978 | foreach($this->Values as $value) {
979 |
980 | $resultado = eval('return (' . $condicion . ');');
981 |
982 | if ($resultado) {
983 | $fieldValue = $value->$sumField;
984 |
985 | if (isset($fieldValue) && is_numeric($fieldValue)) {
986 | $sumResult += $fieldValue * 1;
987 | }
988 | }
989 | }
990 |
991 | return $sumResult;
992 | }
993 |
994 | public function Max($field) {
995 |
996 | if ($this->GetLocalCache()->LastMaxField != $field) {
997 |
998 | // Revisar en el indice principal si el campo es la llave
999 | if ($this->Key != "" && $field == $this->Key) {
1000 |
1001 | if (!isset($this->GetLocalCache()->PrimaryIndex)) {
1002 | // Crear el indice
1003 | $this->CreatePrimaryIndex($this->Key);
1004 | }
1005 |
1006 | if (count($this->GetLocalCache()->PrimaryIndex) > 0) {
1007 | // Buscar en el indice principal el primer elemento
1008 | $idx = array_key_last($this->GetLocalCache()->PrimaryIndex);
1009 |
1010 | if (isset($idx)) {
1011 | $this->GetLocalCache()->LastMax = $idx;
1012 | }
1013 | }
1014 | else {
1015 | $this->GetLocalCache()->LastMax = null;
1016 | }
1017 | }
1018 | // Probar utilizando el índice secundario del campo si no es la llave
1019 | else {
1020 | if (!isset($this->GetLocalCache()->SecondaryIndexes[$field])) {
1021 | // Crear el indice
1022 | $this->CreateSecondaryIndexes([$field]);
1023 | }
1024 |
1025 | $idx = array_key_last($this->GetLocalCache()->SecondaryIndexes[$field]);
1026 |
1027 | if (isset($idx)) {
1028 | $this->GetLocalCache()->LastMax = $idx;
1029 | }
1030 | else {
1031 | $this->GetLocalCache()->LastMax = null;
1032 | }
1033 | }
1034 |
1035 | // Actualizar caché
1036 | $this->GetLocalCache()->LastMaxField = $field;
1037 | }
1038 |
1039 | return $this->GetLocalCache()->LastMax;
1040 | }
1041 |
1042 | public function Min($field) {
1043 |
1044 | $dtStartMonitor = microtime(true);
1045 |
1046 | if ($this->GetLocalCache()->LastMinField != $field) {
1047 |
1048 | // Revisar en el indice principal si el campo es la llave
1049 | if ($this->Key != "" && $field == $this->Key) {
1050 |
1051 | if (!isset($this->GetLocalCache()->PrimaryIndex)) {
1052 | // Crear el indice
1053 | $this->CreatePrimaryIndex($this->Key);
1054 | }
1055 |
1056 | if (count($this->GetLocalCache()->PrimaryIndex) > 0) {
1057 | // Buscar en el indice principal el primer elemento
1058 | $idx = array_key_first($this->GetLocalCache()->PrimaryIndex);
1059 |
1060 | if (isset($idx)) {
1061 | $this->GetLocalCache()->LastMin = $idx;
1062 | }
1063 | }
1064 | else {
1065 | $this->GetLocalCache()->LastMin = null;
1066 | }
1067 | }
1068 | // Probar utilizando el índice secundario del campo si no es la llave
1069 | else {
1070 | if (!isset($this->GetLocalCache()->SecondaryIndexes[$field])) {
1071 | // Crear el indice
1072 | $this->CreateSecondaryIndexes([$field]);
1073 | }
1074 |
1075 | $idx = array_key_first($this->GetLocalCache()->SecondaryIndexes[$field]);
1076 |
1077 | if (isset($idx)) {
1078 | $this->GetLocalCache()->LastMin = $idx;
1079 | }
1080 | else {
1081 | $this->GetLocalCache()->LastMin = null;
1082 | }
1083 | }
1084 |
1085 | // Actualizar caché
1086 | $this->GetLocalCache()->LastMinField = $field;
1087 | }
1088 |
1089 | $dtEndMonitor = microtime(true);
1090 |
1091 | Monitor::$MinExecutions++;
1092 | Monitor::$MinExecutionTime += ($dtEndMonitor - $dtStartMonitor);
1093 |
1094 | return $this->GetLocalCache()->LastMin;
1095 | }
1096 |
1097 | public function IndexedMin($field) {
1098 |
1099 | $dtStartMonitor = microtime(true);
1100 |
1101 | if ($this->GetLocalCache()->LastMinField != $field) {
1102 |
1103 | // Primero probar utilizando el índice del campo si este existe
1104 | // (no se creará un índice automático puesto que el campo puede no ser de tipo INT y el índice no funcionaría)
1105 | if (isset($this->GetLocalCache()->SecondaryIndexes[$field])) {
1106 | }
1107 |
1108 | // Actualizar caché
1109 | $this->GetLocalCache()->LastMinField = $field;
1110 |
1111 | $parts = explode(" ", $field);
1112 | $fieldName = $parts[0];
1113 |
1114 | $order = $this->OrderedBy($fieldName);
1115 |
1116 | // Actualizar caché
1117 | $this->GetLocalCache()->LastMin = $order->First()->$fieldName;
1118 | }
1119 |
1120 | $dtEndMonitor = microtime(true);
1121 |
1122 | Monitor::$IndexedMinExecutions++;
1123 | Monitor::$IndexedMinExecutionTime += ($dtEndMonitor - $dtStartMonitor);
1124 |
1125 | return $this->GetLocalCache()->LastMin;
1126 | }
1127 |
1128 | public function ItemMax($field) {
1129 |
1130 | if ($this->GetLocalCache()->LastItemMaxField != $field) {
1131 |
1132 | // Actualizar caché
1133 | $this->GetLocalCache()->LastItemMaxField = $field;
1134 |
1135 | $parts = explode(" ", $field);
1136 | $fieldName = $parts[0];
1137 |
1138 | $order = $this->OrderedBy($fieldName);
1139 |
1140 | // Actualizar caché
1141 | $this->GetLocalCache()->LastItemMax = $order->Last();
1142 | }
1143 |
1144 | return $this->GetLocalCache()->LastItemMax;
1145 | }
1146 |
1147 | public function ItemMin($field) {
1148 |
1149 | if ($this->GetLocalCache()->LastMinItemField != $field) {
1150 |
1151 | // Actualizar caché
1152 | $this->GetLocalCache()->LastMinItemField = $field;
1153 |
1154 | $parts = explode(" ", $field);
1155 | $fieldName = $parts[0];
1156 |
1157 | $order = $this->OrderedBy($fieldName);
1158 |
1159 | // Actualizar caché
1160 | $this->GetLocalCache()->LastMinItem = $order->First();
1161 | }
1162 |
1163 | return $this->GetLocalCache()->LastMinItem;
1164 | }
1165 |
1166 | public function Distinct($field) {
1167 |
1168 | if ($this->GetLocalCache()->LastDistinctField != $field) {
1169 |
1170 | // Actualizar caché
1171 | $this->GetLocalCache()->LastDistinctField = $field;
1172 |
1173 | // Enumerar la colección sin repetir el campo
1174 | $result = array();
1175 |
1176 | foreach($this->Values as $value) {
1177 | $itemFieldValue = $value->$field;
1178 |
1179 | if (!isset($result[$itemFieldValue])) {
1180 | $result[$itemFieldValue] = $value->$field;
1181 | }
1182 | }
1183 |
1184 | // Actualizar caché
1185 | $this->GetLocalCache()->LastDistinct = $result;
1186 | }
1187 |
1188 | return $this->GetLocalCache()->LastDistinct;
1189 | }
1190 |
1191 | public function DistinctItem($field = "") {
1192 |
1193 | if ($this->GetLocalCache()->LastDistinctItemField != $field) {
1194 |
1195 | // Actualizar caché
1196 | $this->GetLocalCache()->LastDistinctItemField = $field;
1197 |
1198 | // Enumerar la colección sin repetir el campo
1199 | $result = array();
1200 |
1201 | foreach($this->Values as $value) {
1202 | $itemFieldValue = $value->$field;
1203 |
1204 | if (!isset($result[$itemFieldValue])) {
1205 | $result[$itemFieldValue] = $value;
1206 | }
1207 | }
1208 |
1209 | // Actualizar caché
1210 | $this->GetLocalCache()->LastDistinctItem = new GenericCollection(
1211 | Key: $this->Key,
1212 | DtoName: $this->DtoName,
1213 | Values: $result
1214 | );
1215 | }
1216 |
1217 | return $this->GetLocalCache()->LastDistinctItem;
1218 | }
1219 |
1220 | public function SingleEqualSignReplace($condicion) {
1221 | $fase1 = str_replace("==", "<>", $condicion);
1222 | $fase2 = str_replace("=", "==", $fase1);
1223 |
1224 | return str_replace("<>", "==", $fase2);
1225 | }
1226 |
1227 |
1228 | // Monitoring functions
1229 | public static function ResetMonitor() {
1230 | Monitor::$FromTimeExecutions = 0;
1231 | Monitor::$FromTimeExecutionTime = 0;
1232 | Monitor::$MergeChildrenExecutions = 0;
1233 | Monitor::$MergeChildrenExecutionTime = 0;
1234 | Monitor::$KeyIndexExecutions = 0;
1235 | Monitor::$KeyIndexExecutionTime = 0;
1236 | Monitor::$MinExecutions = 0;
1237 | Monitor::$MinExecutionTime = 0;
1238 | Monitor::$IndexedMinExecutions = 0;
1239 | Monitor::$IndexedMinExecutionTime = 0;
1240 | }
1241 |
1242 | public static function GetMonitorVars() {
1243 | return (object)[
1244 | "FromTimeExecutions" => Monitor::$FromTimeExecutions,
1245 | "FromTimeExecutionTime" => Monitor::$FromTimeExecutionTime,
1246 | "FromTimeAverageTime" => (Monitor::$FromTimeExecutions == 0) ? 0 : (Monitor::$FromTimeExecutionTime / Monitor::$FromTimeExecutions),
1247 | "MergeChildrenExecutions" => Monitor::$MergeChildrenExecutions,
1248 | "MergeChildrenExecutionTime" => Monitor::$MergeChildrenExecutionTime,
1249 | "MergeChildrenAverageTime" => (Monitor::$MergeChildrenExecutions == 0) ? 0 : (Monitor::$MergeChildrenExecutionTime / Monitor::$MergeChildrenExecutions),
1250 | "KeyIndexExecutions" => Monitor::$KeyIndexExecutions,
1251 | "KeyIndexExecutionTime" => Monitor::$KeyIndexExecutionTime,
1252 | "MinExecutions" => Monitor::$MinExecutions,
1253 | "MinExecutionTime" => Monitor::$MinExecutionTime,
1254 | "MinExecutionAverageTime" => (Monitor::$MinExecutions == 0) ? 0 : (Monitor::$MinExecutionTime / Monitor::$MinExecutions),
1255 | "IndexedMinExecutions" => Monitor::$IndexedMinExecutions,
1256 | "IndexedMinExecutionTime" => Monitor::$IndexedMinExecutionTime,
1257 | "IndexedMinExecutionAverageTime" => (Monitor::$IndexedMinExecutions == 0) ? 0 : (Monitor::$IndexedMinExecutionTime / Monitor::$IndexedMinExecutions)
1258 | ];
1259 | }
1260 |
1261 | // Getters
1262 | // *******************************************
1263 | public function GetValue($property) {
1264 | return $this->$property;
1265 | }
1266 |
1267 | /**
1268 | * Reemplaza el token, teniendo la precaucion de realizar una comparación de palabra completa
1269 | */
1270 | public static function TokenReplace($search, $replace, $subject) {
1271 | return preg_replace("/\b" . $search . "\b/i", $replace, $subject);
1272 | }
1273 |
1274 | public function GetKey() {
1275 | return $this->Key;
1276 | }
1277 |
1278 | public function GetDtoName() {
1279 | return $this->DtoName;
1280 | }
1281 |
1282 | }
--------------------------------------------------------------------------------
Total de líneas: 1282
================================================================================
================================================================================
ARCHIVO #59: src/Collection/GenericDefinition.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Collection/GenericDefinition.php
Tamaño: 2.43 KB
--------------------------------------------------------------------------------
1 | ValidateRequiredFields($definition);
23 |
24 | if (isset($errors)) {
25 | $mensaje = "";
26 |
27 | foreach($errors as $error) {
28 | if ($mensaje != "") $mensaje .= "\n";
29 | $mensaje.= $error;
30 | }
31 |
32 | throw new \Exception("No se han especificado los siguientes parametros obligatorios en la definicion:\n" . $mensaje);
33 | }
34 | }
35 | */
36 |
37 | // Escribir las propiedades en el objeto final
38 | foreach($properties as $propname => $propvalue) {
39 | // Seteamos la propiedad
40 | if (isset($definition[$propname])) {
41 | $this->$propname = $definition[$propname];
42 | }
43 | }
44 |
45 | // Validacion
46 | if (isset($validatorClass) && $validatorClass != "") {
47 |
48 | // Instanciar el validador
49 | $this->Validator = new $validatorClass($this);
50 |
51 | // Ejecutar la validacion
52 | try {
53 | $this->Validator->RunValidations($definition);
54 | }
55 | catch (\Exception $e) {
56 | throw ($e);
57 | }
58 |
59 | }
60 | }
61 |
62 | // Getters
63 | // *******************************************
64 | public function GetValue($property) {
65 | return $this->$property;
66 | }
67 |
68 | // protected function ValidateRequiredFields($definition) {
69 | // // Verificar que todos los campos de la definicion han sido especificados
70 | // $errors = array();
71 |
72 | // $vars = get_object_vars($this);
73 |
74 | // foreach($vars as $prop => $value) {
75 | // if (!isset($definition[$prop])) {
76 | // array_push($errors, "El campo $prop no ha sido especificado en la definicion");
77 | // }
78 | // }
79 |
80 | // if (count($errors) > 0) {
81 | // return $errors;
82 | // }
83 | // else {
84 | // return null;
85 | // }
86 | // }
87 |
88 | }
--------------------------------------------------------------------------------
Total de líneas: 88
================================================================================
================================================================================
ARCHIVO #60: src/Collection/GenericValidator.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Collection/GenericValidator.php
Tamaño: 3.51 KB
--------------------------------------------------------------------------------
1 | Element = $element;
24 | $this->LoadValidations();
25 | }
26 |
27 | // Obtener las propiedades y los validadores del objeto actual
28 | private function LoadValidations() {
29 |
30 | if (!isset($this->Element))
31 | return;
32 |
33 | $entity = new \ReflectionClass(get_class($this->Element));
34 | $propiedades = get_class_vars($entity->getName());
35 |
36 | foreach($propiedades as $propiedad=>$valor) {
37 | $prop = new \ReflectionProperty($entity->getName(), $propiedad);
38 | $annotations = DocComment::GetPropertyAnnotations($prop, "\n");
39 |
40 | foreach($annotations as $annotation) {
41 | switch(strtolower($annotation->Name)) {
42 | case "validation" :
43 | array_push($this->Validations, (object) ["Property" => $prop, "Validation" => $annotation->Value]);
44 | break;
45 | case "required" :
46 | array_push($this->RequiredFields, $propiedad);
47 | break;
48 | }
49 | }
50 |
51 | }
52 | }
53 |
54 | public function RunValidations(array $definition = array()) {
55 |
56 | $mensajes = "";
57 |
58 | // Evaluar los campos que no se cargaron en la definicion y que son requeridos
59 | foreach($this->RequiredFields as $propiedad) {
60 | if (!isset($definition[$propiedad])) {
61 | if ($mensajes!="") $mensajes .= "\n";
62 | $mensajes .= "Propiedad: \"" . $propiedad . "\", No se ha definido esta propiedad obligatoria";
63 | }
64 | }
65 |
66 | foreach($this->Validations as $validation) {
67 |
68 | $sentence = $validation->Validation;
69 | $property = $validation->Property->name;
70 |
71 | // Reemplazar las ocurrencias de la propiedad
72 | $sentence = str_replace('@prop', '$this->Element->'.$property, $sentence);
73 |
74 | // Reemplazar llamadas a metodos
75 | $sentence = str_replace('@', '$this->', $sentence);
76 |
77 | // Ejecutar la validacion
78 | $result = eval("return (" . $sentence . ");");
79 |
80 | if (!$result) {
81 | if ($mensajes!="") $mensajes .= "\n";
82 | $mensajes .= "Propiedad: \"" . $property . "\", Validacion: [ " . $sentence . " ]";
83 | }
84 | }
85 |
86 | if ($mensajes != "") {
87 | throw new Exception($mensajes);
88 | }
89 |
90 | return true;
91 | }
92 |
93 | // General purpose validators
94 | // ***************************************************************
95 | public function is_date($date, $format) {
96 |
97 | $d = \DateTime::createFromFormat($format, $date);
98 |
99 | return $d && $d->format($format) === $date;
100 | }
101 |
102 | public function is_valid_array($array) {
103 | return (isset($array) && is_array($array) && count($array) > 0);
104 | }
105 |
106 | public function is_collection($collection) {
107 | return ($collection instanceof GenericCollection);
108 | }
109 |
110 | public function instance_of($property, $className) {
111 |
112 | $plop = ($property instanceof $className);
113 |
114 | return ($property instanceof $className);
115 | }
116 | }
--------------------------------------------------------------------------------
Total de líneas: 116
================================================================================
================================================================================
ARCHIVO #61: src/Collection/MergeDefinition.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Collection/MergeDefinition.php
Tamaño: 514 bytes
--------------------------------------------------------------------------------
1 | decodeMultiple($jsonData, static::class);
64 | }
65 | else {
66 | $configResult = $jsonDecoder->decode($jsonData, static::class);
67 | }
68 |
69 | return $configResult;
70 | }
71 |
72 |
73 | }
--------------------------------------------------------------------------------
Total de líneas: 73
================================================================================
================================================================================
ARCHIVO #63: src/Configuration/BundleConfig.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Configuration/BundleConfig.php
Tamaño: 1.65 KB
--------------------------------------------------------------------------------
1 | __ControllerContainer->methods;
58 |
59 | $userMenu = array();
60 | if (isset($methods) && isset($menus)) {
61 |
62 | foreach ($menus as $idMenu => $menu) {
63 |
64 | // Revisar si el menú está autorizado
65 | $authorizedMenu = self::GetMenuIfAuthorized($menu, $dispatcher, $idioma, $locale);
66 |
67 | // es menu suelto o tiene submenu?
68 | if (count($menu->Items) == 0) { // <- menú suelto sin hijos
69 | if (isset($authorizedMenu)) {
70 | $userMenu[$idMenu] = $authorizedMenu;
71 | }
72 | }
73 | else { // <- menú principal con hijos
74 |
75 | // Se deben chequear primero los hijos, si al menos tiene 1, entonces agregamos el menú padre
76 | $childMenus = array();
77 |
78 | foreach($menu->Items as $childMenu) {
79 | $child = (new BaseMapper((object)$childMenu))->MapTo(MenuConfig::class);
80 | $authorizedChildMenu = self::GetMenuIfAuthorized($child, $dispatcher, $idioma, $locale);
81 |
82 | if (isset($authorizedChildMenu)) {
83 | array_push($childMenus, $authorizedChildMenu);
84 | }
85 | }
86 |
87 | // Revisar si exiten menus hijos
88 | //
89 | if (count($childMenus) > 0) {
90 | // Si tiene hijos autorizados, autorizamos el menu padre también
91 | $menu->Items = $childMenus;
92 | $userMenu[$idMenu] = $menu;
93 | }
94 | }
95 | }
96 | }
97 |
98 | return $userMenu;
99 | }
100 |
101 | private static function GetMenuIfAuthorized(MenuConfig $menu, BaseDispatcher $dispatcher, $idioma, $locale) {
102 |
103 | // Buscar primero la ruta URI del menu en los métodos
104 | //
105 | $methods = $dispatcher->__ControllerContainer->methods;
106 | $foundRoutes = $methods->Where('FullPath == "' . $menu->Uri . '"');
107 |
108 | // Si no encontramos el URI en los métodos, buscar si existe a nivel de controlador
109 | //
110 | if (!isset($foundRoutes) || !$foundRoutes || $foundRoutes->Count() == 0) {
111 | $found = array();
112 | foreach($dispatcher->__ControllerContainer->controllers as $controller) {
113 | if ($controller->ControllerRoute->FullPath == $menu->Uri)
114 | array_push($found, $controller->ControllerRoute);
115 | }
116 |
117 | if (count($found) > 0) {
118 | $foundRoutes = new GenericCollection(
119 | Key : 'FullPath',
120 | DtoName : Route::class,
121 | Values : $found
122 | );
123 | }
124 | }
125 |
126 | if (isset($foundRoutes) && $foundRoutes && $foundRoutes->Count() > 0) {
127 | $route = $foundRoutes->First();
128 |
129 | // agregar si está autorizado o el menu es público
130 | //
131 | if ($route->Authorization == 'ALLOW_ALL' || $dispatcher->HasAnyRol($route->Roles)) {
132 | $result = new MenuConfig();
133 |
134 | if (strpos($menu->Description, '@@')) {
135 | $descripcion = BaseController::RenderMensaje($menu->Description, '@@', $idioma, $locale);
136 |
137 | foreach($descripcion as $key => $value) {
138 | $result->Description = $value;
139 | break;
140 | }
141 | }
142 | else {
143 | $result->Description = $menu->Description;
144 | }
145 |
146 | $result->Icon = $menu->Icon;
147 | $result->Uri = $menu->Uri;
148 | $result->Decorators = $menu->Decorators;
149 | $result->Items = array();
150 |
151 | foreach($result->Decorators as $decorator) {
152 | if ($decorator['Type'] == 'TITULO' && strpos($decorator['Definition'], '@@')) {
153 | $descripcion = BaseController::RenderMensaje($decorator['Definition'], '@@', $idioma, $locale);
154 |
155 | foreach($descripcion as $key => $value) {
156 | $decorator['Definition'] = $value;
157 | break;
158 | }
159 | }
160 | }
161 |
162 | return $result;
163 | }
164 | }
165 |
166 | return null;
167 | }
168 |
169 | public static function GetUserMenuWidget($funcs) {
170 |
171 | $itemsMenuSistema = [];
172 |
173 | if (isset($funcs)) {
174 | foreach($funcs as $idFunc=>$func) {
175 |
176 | // Ver si es un menu suelto o un menu con items
177 | if (count($func->Items) == 0) {
178 | $activa = ($_SERVER['REQUEST_URI'] == $func->Uri) ? " active " : "";
179 |
180 | if ($func->Description == '') {
181 | $iconclass = 'menu-icono';
182 | }
183 | else {
184 | $iconclass = 'menu-icono-withtext';
185 | }
186 |
187 | $nuevoMenu = new MenuItem(
188 | Title: $func->Description,
189 | Action: $func->Uri,
190 | Classes: ['menu-icon-text'],
191 | Icon: ($func->Icon != '') ? new FaIcon(Name: $func->Icon, Classes: [$iconclass]) : null,
192 | Active: ($_SERVER['REQUEST_URI'] == $func->Uri)
193 | );
194 | }
195 | else {
196 | $activaMnu = false;
197 | foreach ($func->Items as $idItem=>$item)
198 | {
199 | if ($_SERVER['REQUEST_URI'] == $item->Uri) {
200 | $activaMnu = true;
201 | break;
202 | }
203 | }
204 |
205 | $menuItems = [];
206 |
207 | foreach ($func->Items as $idItem=>$item)
208 | {
209 | $activa = ($_SERVER['REQUEST_URI'] == $item->Uri);
210 |
211 | // Agregar decoradores
212 | if (count($item->Decorators) > 0) {
213 | foreach($item->Decorators as $decorator) {
214 | if ($decorator['Type'] == 'TITULO') {
215 | array_push($menuItems, new ActionMenuTitle(
216 | Content: $decorator['Definition'],
217 | Classes: ['menu-titulo']
218 | ));
219 | }
220 | else if ($decorator['Type'] == 'SEPARATOR') {
221 | array_push($menuItems, new ActionMenuSeparator(
222 | Classes: ['menu-separador']
223 | ));
224 | }
225 | else if ($decorator['Type'] == 'MINISEPARATOR') {
226 | array_push($menuItems, new ActionMenuMiniSeparator(
227 | Classes: ['menu-mini-separador']
228 | ));
229 | }
230 | }
231 | }
232 |
233 | $icon = null;
234 | if (isset($item->Icon) && $item->Icon != '') {
235 | $icon = new FaIcon(
236 | Name: $item->Icon,
237 | Classes: ['menu-item-icono']
238 | );
239 | }
240 |
241 | // Agregar el item de menu
242 | array_push($menuItems, new ActionMenuItem(
243 | Classes: ['dropdown'],
244 | Action: $item->Uri,
245 | Content: $item->Description,
246 | Icon: $icon,
247 | Active: $activa
248 | ));
249 | }
250 |
251 | $nuevoMenu = new ActionMenu(
252 | Title: $func->Description,
253 | Items: $menuItems,
254 | Classes: [$activaMnu],
255 | Active: $activaMnu
256 | );
257 | }
258 |
259 | array_push($itemsMenuSistema, $nuevoMenu);
260 | }
261 | }
262 |
263 | $menuSistema = new Menu(
264 | Items: $itemsMenuSistema,
265 | ContainerClasses: ['navbar-left'],
266 | MenuClasses: ['nav navbar-nav no-borders']
267 | );
268 |
269 | return $menuSistema;
270 | }
271 | }
--------------------------------------------------------------------------------
Total de líneas: 271
================================================================================
================================================================================
ARCHIVO #67: src/Configuration/RedisConfig.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Configuration/RedisConfig.php
Tamaño: 908 bytes
--------------------------------------------------------------------------------
1 | Exists($idRestriction)) {
53 | $restriction = $restrictions->Find($idRestriction);
54 |
55 | $roles = $restriction->Roles;
56 | $positiveAction = $restriction->PositiveAction;
57 | $negativeAction = $restriction->NegativeAction;
58 |
59 | if (isset($roles) && isset($positiveAction) && isset($negativeAction)) {
60 | // Verificar si el perfil consultado tiene alguno de estos roles
61 | if (PerfilSvc::HasAnyRol($perfil, $roles)) {
62 | return $positiveAction;
63 | }
64 | else {
65 | return $negativeAction;
66 | }
67 | }
68 | }
69 |
70 | return "Hide";
71 | }
72 | }
--------------------------------------------------------------------------------
Total de líneas: 72
================================================================================
================================================================================
ARCHIVO #69: src/Configuration/SystemConfig.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Configuration/SystemConfig.php
Tamaño: 2.40 KB
--------------------------------------------------------------------------------
1 | strtolower($_SERVER['HTTP_HOST'])
82 | ];
83 | }
84 | else {
85 | return [];
86 | }
87 |
88 | }
89 | }
--------------------------------------------------------------------------------
Total de líneas: 89
================================================================================
================================================================================
ARCHIVO #70: src/Controllers/ActionResult.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Controllers/ActionResult.php
Tamaño: 865 bytes
--------------------------------------------------------------------------------
1 | imageReader = $assetManagerFactory->GetImageReaderAM();
36 | $this->assetReader = $assetManagerFactory->GetImageReaderAM();
37 | $this->controller = $forcedController;
38 | }
39 |
40 | public function Redirect(string $uri) {
41 | header("Location: $uri");
42 | die();
43 | }
44 |
45 | public static function GetPathExtension($uri) {
46 |
47 | $path_parts = pathinfo($uri);
48 |
49 | return isset($path_parts['extension']) ? $path_parts['extension'] : '';
50 | }
51 |
52 | private function GetViewFileLocation($viewname) {
53 |
54 | if ($this->controller != '') {
55 | $controllerName = $this->controller;
56 | }
57 | else {
58 | $classFullName = str_replace('Application\\Controllers\\', '', (new \ReflectionClass(get_called_class()))->getName());
59 | $controllerName = str_replace('\\', '/', str_replace('Controller', '', $classFullName));
60 | }
61 |
62 | $masterPath = VIEW_ROOT . '/' . $controllerName;
63 |
64 | return $masterPath . '/' . $viewname . 'View.php';
65 | }
66 |
67 | public function RenderView($view, $data = null) {
68 |
69 | Log::ErrorLog('FWK-Inicio Renderizado');
70 |
71 | $viewFilePath = $this->GetViewFileLocation($view);
72 |
73 | Log::ErrorLog('FWK-Inicio Renderizado');
74 |
75 | return $this->RenderFile($viewFilePath, $data);
76 | }
77 |
78 | private function RenderFile($file, $data = null) {
79 |
80 | Log::ErrorLog('FWK-Inicio RenderFile - File: ' . $file);
81 |
82 | //$dtInicio = microtime(true);
83 |
84 | if (file_exists($file)) {
85 | Log::ErrorLog('FWK-RenderFile fin file_exists($file)');
86 | ob_start();
87 | Log::ErrorLog('FWK-RenderFile fin ob_start()');
88 | include( $file );
89 | Log::ErrorLog('FWK-RenderFile fin include( $file )');
90 | $content = ob_get_contents();
91 | Log::ErrorLog('FWK-RenderFile fin ob_get_contents()');
92 | ob_end_clean();
93 | Log::ErrorLog('FWK-RenderFile fin ob_end_clean');
94 | }
95 | else {
96 | return "No existe la vista especificada (".$file.")
";
97 | }
98 |
99 | //$dtFin = microtime(true);
100 |
101 | // Log::ErrorLog('FWK-RenderFile fin ob_clean - Time: ' . round(($dtFin - $dtInicio), 4) . ' segs.');
102 |
103 | // Obtener el layout si es que existe
104 |
105 | // La funcion "ObtenerRenderSections" devuelve un arreglo de pares "Id => StringTotal"
106 | // Ej: "guest" => "@@Layout(guest)"
107 | $layouts = $this->ObtenerRenderSections($content, '@@Layout');
108 |
109 | Log::ErrorLog('FWK-Fin Obtener RenderSections');
110 |
111 | if (count($layouts) > 0) {
112 | // Solo se considerará el primer layout
113 | if (count($layouts) > 1) {
114 | return "Error de definición se ha definido más de 1 layout para esta vista (".$view.")
";
115 | }
116 | else {
117 | // Obtener el layout
118 | foreach($layouts as $layout=>$searchString) {
119 |
120 | Log::ErrorLog('FWK-Inicio Busqueda Layout');
121 |
122 | $layoutFilePath = LAYOUT_ROOT . '/' . $layout . 'Layout.php';
123 | $layoutContent = "";
124 |
125 | if (isset($layout) && $layout != "") {
126 |
127 | // Ver si existe el archivo
128 | if (file_exists($layoutFilePath)) {
129 | ob_start();
130 | include( $layoutFilePath );
131 | $layoutContent = ob_get_contents();
132 | ob_end_clean();
133 | }
134 | else {
135 | return "No existe el layout (".$layoutFilePath.") especificado en esta vista (".$file.")
";
136 | }
137 | }
138 |
139 | Log::ErrorLog('FWK-Fin ob_end layout');
140 |
141 | $content = $this->RenderContent($content, $layoutContent, $searchString);
142 |
143 | // Solo se debe ejecutar 1 vez.
144 | break;
145 | }
146 |
147 | }
148 |
149 | Log::ErrorLog('FWK-Fin Renderfile');
150 | }
151 |
152 | // Renderizar las secciones
153 | $content = $this->RenderSections($content, $data);
154 |
155 | // Renderizar las cadenas de texto
156 | // Ejemplo: @@{MsgWrongPassword} se convierte en "Wrong username or password" (sin las comillas)
157 |
158 | //$prueba = $this->RenderStrings($content);
159 |
160 | Log::ErrorLog('FWK-Inicio RenderStrings');
161 | $content = $this->RenderStrings($content);
162 | Log::ErrorLog('FWK-Fin RenderStrings');
163 |
164 |
165 | Log::ErrorLog('FWK-Fin RenderFile');
166 |
167 | return $content;
168 | }
169 |
170 |
171 | public function RenderContent($content, $layoutContent = '', $searchString = '') {
172 |
173 | Log::ErrorLog('FWK-Inicio RenderContent');
174 |
175 | // Encontrar los bundles de la vista e inyectarlos en el layout
176 | // La funcion "ObtenerCadenasReemplazoBundles" devuelve un arreglo de pares "CadenaTotal" => "reemplazo"
177 | // Ej: '@@IncludeStyleBundle(estilosCss)' => ''
178 | $renderStyleResults = $this->ObtenerCadenasReemplazoBundles($content, '@@IncludeStyleBundle');
179 |
180 | Log::ErrorLog('FWK-Fin ObtenerCadenasReemplazoBundles');
181 |
182 | if (count($renderStyleResults) > 0) {
183 |
184 | $insertarStyle = "";
185 | foreach($renderStyleResults as $searchBundle=>$replaceBundle) {
186 | // Acumulamos el código para insertar en el layout
187 | $insertarStyle .= $replaceBundle;
188 | // Borramos la definición desde la vista (aquí no será útil)
189 | $content = \str_replace($searchBundle, '', $content);
190 | }
191 |
192 | // Buscamos en el layout dónde insertar el código
193 | // Debemos reemplazar la llave "@@RenderViewStyles()"
194 | // Reemplazamos en el layout el código acumulado
195 | if (isset($layoutContent))
196 | $layoutContent = \str_replace('@@RenderViewStyle()', $insertarStyle, $layoutContent);
197 |
198 | } else {
199 | // Si la vista no ha definido bundle de estilo, en el layout
200 | // debemos quitar la referencia que pueda existir
201 | if (isset($layoutContent))
202 | $layoutContent = \str_replace('@@RenderViewStyle()', '', $layoutContent);
203 | }
204 |
205 | Log::ErrorLog('FWK-Fin RenderStyles');
206 |
207 | // Ej: '@@IncludeScriptBundle(vistaJS)' => '' . "\n";
703 | case "javascript":
704 | return '' . "\n";
705 | case "css":
706 | return '' . "\n";
707 | case "font":
708 | return '' . "\n";
709 | default:
710 | return $filePath;
711 | }
712 | }
713 |
714 | // public function RenderWsResult($idError = 0, $msgError = '', $msgFriendly = '', $data = null) {
715 | // $wsResult = new StandardJsonResultWS();
716 |
717 | // $wsResult->IdError = $idError;
718 | // $wsResult->MsgError = $msgError;
719 | // $wsResult->MsgFriendly = $msgFriendly;
720 | // $wsResult->Data = $data;
721 |
722 | // return $wsResult;
723 | // }
724 |
725 |
726 | public function EncodeWsResult($wsResult) {
727 | return json_encode($wsResult, JSON_UNESCAPED_UNICODE);
728 | }
729 |
730 | public function RenderJsonResult($idError = 0, $msgError = '', $msgFriendly = '', $data = null) {
731 | $json = new StandardJsonResultWS();
732 |
733 | $json->IdError = $idError;
734 | $json->MsgError = $msgError;
735 | $json->MsgFriendly = $msgFriendly;
736 | $json->Data = $data;
737 |
738 | $encoded = json_encode($json, JSON_UNESCAPED_UNICODE);
739 |
740 | return $encoded;
741 | }
742 |
743 | public function DecodeJsonParameter($jsonParameter, $class) {
744 | $jsonDecoder = new JsonDecoder();
745 |
746 | return $jsonDecoder->decode($jsonParameter, $class);
747 | }
748 |
749 |
750 | public function GetRequest($name = '') {
751 | if (isset($_REQUEST[$name])) {
752 | return $_REQUEST[$name];
753 | }
754 | else if (isset($_POST[$name])) {
755 | return $_POST[$name];
756 | }
757 | else if (isset($_GET[$name])) {
758 | return $_GET[$name];
759 | }
760 | else {
761 | return file_get_contents('php://input');
762 | }
763 | }
764 |
765 | public function GetObjectParams() {
766 |
767 | $objparams = $_GET;
768 |
769 | if (isset($objparams)) {
770 | return (object) $objparams;
771 | }
772 | else {
773 | return null;
774 | }
775 | }
776 |
777 | public function DecodeJsonRequest($requestId, $class) {
778 | $jsonParameter = $this->GetRequest($requestId); // $_REQUEST[$requestId];
779 |
780 | if (isset($jsonParameter)) {
781 | $jsonDecoder = new JsonDecoder();
782 | return $jsonDecoder->decode($jsonParameter, $class);
783 | }
784 | else {
785 | return null;
786 | }
787 | }
788 |
789 | public function DecodeJsonParameterArray($jsonParameter, $class) {
790 | $jsonDecoder = new JsonDecoder();
791 |
792 | return $jsonDecoder->decodeMultiple($jsonParameter, $class);
793 | }
794 |
795 | protected function DisplayImage($image) {
796 |
797 | header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
798 | header('Expires: January 01, 2013');
799 | header('Pragma: no-cache');
800 | header("Content-Type: image/jpg");
801 |
802 | echo $image;
803 | }
804 |
805 | protected function DownloadXml($file, $filename) {
806 |
807 | header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
808 | header('Expires: January 01, 2013');
809 | header('Pragma: no-cache');
810 | header('Content-Disposition: attachment; filename=' . $filename);
811 | header("Content-Type: application/xml");
812 |
813 | echo $file;
814 | }
815 |
816 | protected function DownloadPdf($file, $filename) {
817 |
818 | //header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
819 | // header('Pragma: no-cache');
820 | //header('Content-Disposition: attachment; filename=' . $filename);
821 | header("Content-Description: File Transfer");
822 | header("Content-Type: application/octet-stream");
823 | header('Content-Type: application/pdf');
824 |
825 |
826 | echo $file;
827 |
828 | }
829 |
830 | }
--------------------------------------------------------------------------------
Total de líneas: 830
================================================================================
================================================================================
ARCHIVO #73: src/Controllers/Chart/LineChartSerie.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Controllers/Chart/LineChartSerie.php
Tamaño: 495 bytes
--------------------------------------------------------------------------------
1 | Texto - $serie->Valor'";
30 | }
31 | else {
32 | $legendText = "";
33 | }
34 |
35 | $series .=
36 | "
37 | {
38 | values: [$serie->Valor],
39 | text: '$serie->Texto',
40 | backgroundColor: '$serie->Color',
41 | $legendText
42 | }
43 | ";
44 | }
45 |
46 | return "\n
47 | {\n
48 | type: 'pie',\n
49 | title: {\n
50 | text: '$titulo'\n
51 | },\n
52 | scale: {\n
53 | 'size-factor':$scale\n
54 | },\n
55 | subtitle: {\n
56 | text: '$subtitulo'\n
57 | },\n
58 | legend: {\n
59 | layout: '$layout',
60 | y: '20px',\n
61 | margin: '$layouttopmargin 5px 5px 5px',\n
62 | adjustLayout: true,\n
63 | },\n
64 | plot: {\n
65 | valueBox: {\n
66 | placement: 'out'\n
67 | }\n
68 | },\n
69 | series: [\n
70 | $series \n
71 | ]\n
72 | }\n
73 | ";
74 | }
75 |
76 | public static function CreateLine(array $lineChartSeries, array $etiquetas, $format) {
77 |
78 | $scaleX = '';
79 | $series = '';
80 |
81 | $scaleX = join(",\n", $etiquetas);
82 |
83 | foreach($lineChartSeries as $line) {
84 |
85 | $label = $line->Label;
86 | $values = join(',', $line->Values);
87 | $highs = join(',', $line->DataHighs);
88 | $color = $line->Color;
89 |
90 | $series .= "\n
91 | {\n
92 | text: '$label',\n
93 | values: [\n
94 | $values\n
95 | ],\n
96 | dataHighs: [\n
97 | $highs\n
98 | ],\n
99 | lineColor: '$color',\n
100 | marker:{\n
101 | backgroundColor:'$color'\n
102 | }\n
103 | },\n
104 | ";
105 | }
106 |
107 | return "\n
108 | {\n
109 | type: 'line',\n
110 | backgroundColor:'#ffffff',\n
111 | legend:{\n
112 | align: 'center',\n
113 | verticalAlign: 'top',\n
114 | backgroundColor:'none',\n
115 | borderWidth: 0,\n
116 | item:{\n
117 | fontColor:'#6a6c6f',\n
118 | cursor: 'hand'\n
119 | },\n
120 | marker:{\n
121 | type:'circle',\n
122 | borderWidth: 0,\n
123 | cursor: 'hand'\n
124 | }\n
125 | },\n
126 | plotarea:{\n
127 | margin:'dynamic 70'\n
128 | },\n
129 | plot:{\n
130 | aspect: 'spline',\n
131 | lineWidth: 2,\n
132 | marker:{\n
133 | borderWidth: 0,\n
134 | size: 5\n
135 | }\n
136 | }, \n
137 | scaleX:{\n
138 | lineColor: '#6a6c6f',\n
139 | zooming: false,\n
140 | minValue: 0,\n
141 | step: 'day',\n
142 | item:{\n
143 | fontColor:'#6a6c6f'\n
144 | },\n
145 | transform:{\n
146 | type: 'date',\n
147 | all: '$format'\n
148 | }, \n
149 | values: [\n
150 | $scaleX\n
151 | ],\n
152 | }, \n
153 | scaleY:{\n
154 | minorTicks: 1,\n
155 | lineColor: '#6a6c6f',\n
156 | tick:{\n
157 | lineColor: '#6a6c6f'\n
158 | },\n
159 | minorTick:{\n
160 | lineColor: '#6a6c6f'\n
161 | },\n
162 | minorGuide:{\n
163 | visible: true,\n
164 | lineWidth: 1,\n
165 | lineColor: '#6a6c6f',\n
166 | alpha: 0.9,\n
167 | lineStyle: 'dashed'\n
168 | },\n
169 | guide:{\n
170 | lineStyle: 'dashed'\n
171 | },\n
172 | item:{\n
173 | fontColor:'#6a6c6f'\n
174 | }\n
175 | },\n
176 | tooltip:{\n
177 | borderWidth: 0,\n
178 | borderRadius: 3\n
179 | },\n
180 | crosshairX:{\n
181 | plotLabel:{\n
182 | multiple: true,\n
183 | borderRadius: 3,\n
184 | text: '%data-highs'\n
185 | },\n
186 | scaleLabel:{\n
187 | backgroundColor:'#53535e',\n
188 | borderRadius: 3\n
189 | },\n
190 | marker:{\n
191 | size: 7,\n
192 | alpha: 0.5\n
193 | }\n
194 | },\n
195 | crosshairY:{\n
196 | lineColor:'#6a6c6f',\n
197 | type:'multiple',\n
198 | scaleLabel:{\n
199 | decimals: 2,\n
200 | borderRadius: 3,\n
201 | offsetX: -5,\n
202 | fontColor: '#2C2C39',\n
203 | bold: true\n
204 | }\n
205 | },\n
206 | tooltip: {\n
207 | text: '%data-highs'\n
208 | },\n
209 | series: [\n
210 | $series \n
211 | ]\n
212 | }\n
213 | ";
214 | }
215 | }
--------------------------------------------------------------------------------
Total de líneas: 215
================================================================================
================================================================================
ARCHIVO #77: src/Controllers/ControllerDefinition.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Controllers/ControllerDefinition.php
Tamaño: 691 bytes
--------------------------------------------------------------------------------
1 | RenderMensaje($message);
22 | }
23 |
24 | // Imprime una fecha con formato dinámico para cambio de idioma en línea
25 | public static function DrawDateTime(\DateTime $fecha, $format, $classes = '') {
26 |
27 | $fmt = Mensaje::_($format);
28 | $fechaDisplay = $fecha->format($fmt);
29 | $Y = $fecha->format('Y');
30 | $m = $fecha->format('m');
31 | $d = $fecha->format('d');
32 | $H = $fecha->format('H');
33 | $i = $fecha->format('i');
34 | $s = $fecha->format('s');
35 |
36 | $html = "$fechaDisplay";
37 |
38 | echo $html;
39 | }
40 |
41 | public static function GetRenderer($controller = "", $forceNew = false) {
42 |
43 | if ($forceNew || self::$Renderer == null || $controller != self::$Controller) {
44 | self::$Renderer = new BaseController($controller);
45 | self::$Controller = $controller;
46 | }
47 |
48 | return self::$Renderer;
49 | }
50 |
51 | public static function DrawSection($title, $info, $classes = "") {
52 | echo "
53 |
54 |
55 |
56 |
57 | ";
58 | }
59 |
60 | public static function DrawInputSection($title, $id, $placeholder, $inputType, $inputAtributes = "", $classes = "") {
61 | echo "
62 |
63 |
64 |
65 |
66 |
67 |
68 | ";
69 | }
70 |
71 | public static function DrawInputTextAreaSection($title, $id, $placeholder, $inputType, $inputAtributes = "", $classes = "") {
72 | echo "
73 |
74 |
75 |
76 |
77 |
78 |
79 | ";
80 | }
81 |
82 | public static function DrawLabelSection($title, $info, $labelType, $classes = "") {
83 |
84 | echo "
85 |
86 |
" . $info . "
87 |
88 |
89 | ";
90 | }
91 |
92 | public static function DrawProgressSection($title, $percentage, $labelType, $classes = "") {
93 |
94 | $progressType = "";
95 |
96 | if ($labelType == "") {
97 | $labelType = "default";
98 | $progressType = "info";
99 | }
100 | else {
101 | $progressType = $labelType;
102 | }
103 |
104 | echo "
105 |
106 |
107 |
108 | $title " . number_format($percentage, 0, '.', ',') . " %
109 |
110 |
111 |
120 |
121 | ";
122 | }
123 |
124 | public static function DrawProgressBar(
125 | $progressId,
126 | $containerStyle = "background-color: #f5f5f5; margin-top: 5px;",
127 | $progressStyle = "background-color: transparent;"
128 | ) {
129 |
130 | echo "
131 |
140 | ";
141 | }
142 |
143 | public static function DrawPanelLabel($title, $size = 0) {
144 |
145 | if (isset($size) && $size > 0) {
146 | $font = "font-size: " . $size . "px;";
147 | }
148 | else {
149 | $font = "";
150 | }
151 |
152 | echo "
153 |
154 | ";
155 | }
156 |
157 | public static function DrawInfoLabel($title) {
158 |
159 | echo "
160 |
161 | ";
162 | }
163 |
164 | public static function DrawPageTile($title, $subtitle) {
165 | echo "
166 |
167 |
168 | " . $title ."
169 |
170 |
171 | " . $subtitle . "
172 | ";
173 | }
174 |
175 | public static function DrawInfoBox($content, $closable = false, $show = true) {
176 |
177 | echo "
178 |
179 | $content
180 |
181 | ";
182 | }
183 |
184 | public static function DrawInfoIcon($text, $placement = "top", $isHtml = false, $icon="fa-info-circle") {
185 | echo "";
186 | }
187 |
188 | public static function DrawValueLabel($value, $style = 'default', $disableOnZero = true) {
189 |
190 | if ($disableOnZero && ($value == 0 || $value == '')) {
191 | echo "0";
192 | }
193 | else {
194 | echo "$value";
195 | }
196 | }
197 |
198 | public static function DrawTabTitle($title = "", $icon = "", $iconsize = 20) {
199 |
200 | if ($title=="") {
201 | echo "
202 |
203 |
204 |
205 | ";
206 | }
207 | else if ($icon=="") {
208 | echo "
209 |
210 | $title
211 |
212 | ";
213 | }
214 | else {
215 | echo "
216 |
217 |
218 | $title
219 |
220 | ";
221 | }
222 | }
223 |
224 | }
--------------------------------------------------------------------------------
Total de líneas: 224
================================================================================
================================================================================
ARCHIVO #79: src/Controllers/ErrorJsonMovilResult.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Controllers/ErrorJsonMovilResult.php
Tamaño: 507 bytes
--------------------------------------------------------------------------------
1 | Usuario = $usuario;
25 | }
26 |
27 | public function Define($nombre, mixed $traza)
28 | {
29 |
30 | $this->CheckTrazas();
31 |
32 | $this->Trazas[$nombre] = $traza;
33 | }
34 |
35 | public function GetValorTraza($nombre)
36 | {
37 | $this->CheckTrazas();
38 |
39 | return $this->Trazas[$nombre];
40 | }
41 |
42 | public function GetAuditJson()
43 | {
44 |
45 | $this->CheckTrazas();
46 | $out = (object)$this->Trazas;
47 |
48 | return json_encode($out, JSON_INVALID_UTF8_SUBSTITUTE | JSON_PRETTY_PRINT);
49 | }
50 |
51 | public function GetAudit()
52 | {
53 | $this->CheckTrazas();
54 | return (object)$this->Trazas;
55 | }
56 |
57 | private function CheckTrazas()
58 | {
59 |
60 | if (!isset($this->Trazas)) {
61 | $this->Trazas = [];
62 |
63 | if (!isset($this->Usuario)) {
64 |
65 | $usuario = $_SESSION['usuario'];
66 |
67 | $usuario = (isset($usuario))
68 | ? (object) [
69 | "IdUsuario" => $usuario->IdUsuario,
70 | "IdCliente" => $usuario->IdCliente,
71 | "IdEmpresa" => $usuario->IdEmpresa,
72 | "LoginName" => $usuario->LoginName,
73 | "Nombre" => $usuario->Nombre,
74 | "IdContacto" => $usuario->IdContacto,
75 | "IdTipoClave" => $usuario->IdTipoClave,
76 | "IndSoloUsoLoginSistema" => $usuario->IndSoloUsoLoginSistema,
77 | "Cargo" => $usuario->Cargo,
78 | "NombrePerfil" => $usuario->NombrePerfil,
79 | "IdPerfil" => (isset($usuario->Perfil)) ? $usuario->Perfil->IdPerfil : -1,
80 | "Cliente" => (isset($usuario->Cliente)) ? $usuario->Cliente->RazonSocial : "",
81 | ]
82 | : null;
83 | }
84 |
85 | $result = BaseDispatcher::GetLastResultForAudit();
86 | $resultType = (isset($result)) ? get_class($result) : '';
87 |
88 | $uriLastInstance = Uri::$LastInstance;
89 | $actionForJson = (isset($uriLastInstance->Action)) ? $uriLastInstance->Action : null;
90 |
91 | $this->Trazas['Fecha'] = "";
92 | $this->Trazas['Usuario'] = $usuario;
93 | $this->Trazas['Cookie'] = $_COOKIE;
94 | $this->Trazas['Server'] = $_SERVER;
95 | $this->Trazas['Request'] = $_REQUEST;
96 | $this->Trazas['Result'] = $result;
97 | $this->Trazas['ResultType'] = $resultType;
98 | $this->Trazas['ResultError'] = str_contains($resultType, "Error");
99 | $this->Trazas['Action'] = $actionForJson;
100 | $this->Trazas['HostName'] = gethostname();
101 | $this->Trazas['ServerIP'] = gethostbyname(gethostname());
102 | }
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
Total de líneas: 105
================================================================================
================================================================================
ARCHIVO #96: src/Core/Cacheable.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Core/Cacheable.php
Tamaño: 1.33 KB
--------------------------------------------------------------------------------
1 | > [[ERRORTYPE]]: [[MESSAGE]]",
29 | public $DateFormat = 'Y-m-d',
30 | public $TimeFormat = 'H:i',
31 | $Flags = 0
32 | ) {
33 | $this->Flags = $Flags;
34 | }
35 | public static function CreateTraceLog($ex, $type)
36 | {
37 | $exception = new ExceptionResult();
38 |
39 | $exception->TypeException = $type;
40 | if ($type == ExceptionTypeEnum::FATAL) {
41 | $exception->Message = $ex["message"];
42 | $exception->Line = $ex["line"];
43 | $exception->FatalType = $ex["type"];
44 | $trace = 'Achivo donde se cae en : ' . $ex["file"];
45 | $exception->Trace = $trace;
46 | } else {
47 | $exception->Message = $ex->getMessage();
48 | $exception->Line = $ex->getLine();
49 | $exception->Code = $ex->getCode();
50 | $exception->Trace = $ex->getTraceAsString();
51 |
52 | if ($type == ExceptionTypeEnum::BUSINESS)
53 | $exception->DebugMessage = $ex->getDebugMessage();
54 | }
55 |
56 | $exception->ServerIP = $_SERVER["SERVER_ADDR"];
57 | $exception->RequestUri = $_SERVER["REQUEST_URI"];
58 | $exception->UserAgent = $_SERVER["HTTP_USER_AGENT"];
59 |
60 | if (isset($_SESSION['usuario'])) {
61 | $usuario = $_SESSION['usuario'];
62 |
63 | $exception->Usuario = (object) [
64 | "IdUsuario" => $usuario->IdUsuario,
65 | "LoginName" => $usuario->LoginName,
66 | ];
67 | }
68 |
69 | $log = self::NewTraceLog();
70 | $log->Log($exception, ErrorType: ErrorTypeEnum::ERROR);
71 | }
72 |
73 | public static function NewTraceLog()
74 | {
75 | $today = (new Date());
76 | $year = $today->format('Y');
77 | $month = $today->format('m');
78 |
79 | $directorio = SITE_ROOT . '/FileData/trace/' . $year . '/' . $month;
80 |
81 | if (!is_dir($directorio)) {
82 | mkdir($directorio, 0775, true);
83 | }
84 |
85 | $filename = 'trace_' . $today->format('Y-m-d') . '.json';
86 |
87 | $fullPath = $directorio . '/' . $filename;
88 |
89 | return new Log(
90 | LogFile: $fullPath,
91 | Format: "\n[[MESSAGE]]",
92 | DateFormat: 'Y-m-d',
93 | TimeFormat: 'H:i:s',
94 | Flags: FILE_APPEND | LOCK_EX
95 | );
96 | }
97 |
98 | public static function NewAuditLog()
99 | {
100 | $today = (new Date());
101 | $year = $today->format('Y');
102 | $month = $today->format('m');
103 |
104 | $directorio = SITE_ROOT . "/FileData/audit/" . $year . '/' . $month;
105 |
106 | if (!is_dir($directorio)) {
107 | mkdir($directorio, 0775, true);
108 | }
109 |
110 | $filename = 'audit_' . $today->format('Y-m-d') . '.json';
111 |
112 | $fullPath = $directorio . '/' . $filename;
113 |
114 | return new Log(
115 | LogFile: $fullPath,
116 | Format: "\n[[MESSAGE]]",
117 | DateFormat: 'Y-m-d',
118 | TimeFormat: 'H:i:s',
119 | Flags: FILE_APPEND | LOCK_EX
120 | );
121 | }
122 |
123 | public function Log($Message, $ErrorType = ErrorTypeEnum::INFO, $Echo = FALSE, $ContinuarAnterior = false)
124 | {
125 |
126 | $dt = new Date();
127 | $date = $dt->format($this->DateFormat);
128 | $time = $dt->format($this->TimeFormat);
129 | $tipoLog = "INFO";
130 |
131 | switch ($ErrorType) {
132 | case "e":
133 | $tipoLog = "ERROR";
134 | break;
135 | case "w":
136 | $tipoLog = "WARNING";
137 | break;
138 | }
139 |
140 | $pathActual = self::GestionarPesoArchivo($this->LogFile, $tipoLog);
141 |
142 | if (gettype($Message) == "object") {
143 | $Message->Fecha = $date . " " . $time;
144 | $Message = json_encode($Message, JSON_INVALID_UTF8_SUBSTITUTE | JSON_PRETTY_PRINT);
145 | } else if (gettype($Message) == "array") {
146 | $Message = (object)(["Fecha" => $date . " " . $time] + $Message);
147 | $Message = json_encode($Message, JSON_INVALID_UTF8_SUBSTITUTE | JSON_PRETTY_PRINT);
148 | }
149 |
150 |
151 | if ($ContinuarAnterior) {
152 | $msg = $Message;
153 | } else {
154 | $msg = str_replace("[[DATE]]", $date, $this->Format);
155 | $msg = str_replace("[[TIME]]", $time, $msg);
156 | $msg = str_replace("[[MESSAGE]]", $Message, $msg);
157 | $msg = str_replace("[[ERRORTYPE]]", $tipoLog, $msg);
158 |
159 | if (!$this->new) {
160 | $msg = "\n" . $msg;
161 | }
162 | $this->new = false;
163 | }
164 |
165 | file_put_contents($pathActual, $msg, $this->Flags);
166 | //fwrite($this->File, $msg);
167 |
168 | if ($Echo) {
169 | echo $msg;
170 | }
171 | }
172 |
173 | public static function ErrorLog($message, $message_type = 0, ?string $destination = '', ?string $additional_headers = '')
174 | {
175 |
176 | if (self::$PhpErrorLogActive) {
177 | error_log($message, $message_type, $destination, $additional_headers);
178 | }
179 |
180 | return true;
181 | }
182 |
183 | public static function GestionarPesoArchivo($fullPath, $tipo)
184 | {
185 | $folder = pathinfo($fullPath, PATHINFO_DIRNAME);
186 | $baseName = $tipo . "_" . pathinfo($fullPath, PATHINFO_FILENAME);
187 | $extension = pathinfo($fullPath, PATHINFO_EXTENSION);
188 | $patchConTipo = "$folder/$baseName.$extension";
189 |
190 | // si no existe el archivo se termina la gestion
191 | if (!file_exists($patchConTipo)) return $patchConTipo;
192 |
193 | // Obtener lista de archivos en la carpeta con el formato específico
194 | $files = glob("$folder/{$baseName}*.$extension");
195 |
196 | // Extraer números de los archivos que coinciden con el formato
197 | $numbers = [];
198 |
199 | foreach ($files as $file) {
200 | $filename = pathinfo($file, PATHINFO_FILENAME);
201 |
202 | // Buscar el número en el nombre del archivo
203 | if (preg_match('/^' . preg_quote($baseName, '/') . '_(\d+)$/', $filename, $matches)) {
204 | $numbers[] = (int)$matches[1];
205 | }
206 | }
207 |
208 | // Ordenar de mayor a menor
209 | rsort($numbers);
210 |
211 | // Obtener el mayor número
212 | $maxNumber = $numbers[0] ?? 0;
213 |
214 | $peso = filesize($patchConTipo);
215 | if (round($peso / (1024 * 1024), 2) > self::$PesoMaximo) {
216 | $newPath = "$folder/$baseName" . "_" . ($maxNumber + 1) . ".$extension";
217 | // se agrega el nuevo archivo
218 | rename($patchConTipo, $newPath);
219 | // se vacia el actual
220 | file_put_contents($patchConTipo, "");
221 | }
222 | return $patchConTipo;
223 | }
224 | }
225 |
--------------------------------------------------------------------------------
Total de líneas: 225
================================================================================
================================================================================
ARCHIVO #102: src/Core/MemoryInfo.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Core/MemoryInfo.php
Tamaño: 1.50 KB
--------------------------------------------------------------------------------
1 | total_kb ?? 0,
43 | $mem->free_kb ?? 0,
44 | $mem->buffers_kb ?? 0,
45 | $mem->cached_kb ?? 0,
46 | $mem->available_kb_kernel ?? 0,
47 | $mem->available_kb_calculated ?? 0,
48 | $mem->total_mb ?? 0,
49 | $mem->available_mb_kernel ?? 0,
50 | $mem->available_mb_calculated ?? 0,
51 | );
52 |
53 | return $result;
54 | }
55 |
56 |
57 | }
--------------------------------------------------------------------------------
Total de líneas: 57
================================================================================
================================================================================
ARCHIVO #103: src/Core/Rut.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Core/Rut.php
Tamaño: 1.14 KB
--------------------------------------------------------------------------------
1 | MapTo($userClass);
34 | }
35 |
36 | if (!isset($decoded) || $decoded->nonce != $tokenValidador) {
37 | $userObj->tokenInvalido = 1;
38 | }
39 |
40 | return $decoded;
41 | }
42 |
43 | public static function ValidarTokenJWK($token, $jwk, $tokenValidador, $userClass = null, $algoritmo = "RS256")
44 | {
45 |
46 | $decoded = JWT::decode($token, JWK::parseKeySet($jwk, $algoritmo));
47 | if ($userClass == null) {
48 | $userObj = $decoded;
49 | } else {
50 | $userObj = (new BaseMapper($decoded))->MapTo($userClass);
51 | }
52 |
53 | if (!isset($decoded) || $decoded->nonce != $tokenValidador) {
54 | $userObj->tokenInvalido = 1;
55 | }
56 |
57 | return $decoded;
58 | }
59 |
60 | public static function ValidarTokenUri($token, $ConfigUri, $tokenValidador, $EsIdToken = true, $userClass = null)
61 | {
62 | $result = HttpHelper::Call(
63 | Method: HttpMethodEnum::GET,
64 | Url: $ConfigUri
65 | );
66 | $configuracion = (object)json_decode($result, true);
67 |
68 | try {
69 | if($EsIdToken){
70 | $jwkUri = HttpHelper::Call(
71 | Method: HttpMethodEnum::GET,
72 | Url: $configuracion->jwks_uri
73 | );
74 | $data = json_decode($jwkUri, true);
75 | $decoded = JWT::decode($token, JWK::parseKeySet($data, $configuracion->id_token_signing_alg_values_supported[0]));
76 | }else{
77 | $decoded =HttpHelper::Call(
78 | Method: HttpMethodEnum::GET,
79 | Url: $configuracion->userinfo_endpoint,
80 | Headers: array('Authorization: Bearer '.$token)
81 | );
82 | $decoded = json_decode($decoded, true);
83 | }
84 |
85 | } catch (\Exception $ex) {
86 | $userObj = new stdClass();
87 | $userObj->tokenInvalido = 1;
88 | $userObj->ex = $ex;
89 |
90 | return $userObj;
91 | }
92 |
93 | if ($userClass == null)
94 | $userObj = $decoded;
95 | else
96 | $userObj = (new BaseMapper((object)$decoded))->MapTo($userClass);
97 |
98 | // Se valida que el token enviado por el servicio de SSO es de la misma consulta que nuestro servicio envio.
99 | if (!isset($decoded) || ($EsIdToken && $decoded->nonce != $tokenValidador)) {
100 | $userObj->tokenInvalido = 1;
101 | }
102 |
103 | return $userObj;
104 | }
105 |
106 | public static function GenerarUuidV4()
107 | {
108 | return sprintf(
109 | '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
110 | // 32 bits for "time_low"
111 | mt_rand(0, 0xffff),
112 | mt_rand(0, 0xffff),
113 |
114 | // 16 bits for "time_mid"
115 | mt_rand(0, 0xffff),
116 |
117 | // 16 bits for "time_hi_and_version",
118 | // four most significant bits holds version number 4
119 | mt_rand(0, 0x0fff) | 0x4000,
120 |
121 | // 16 bits, 8 bits for "clk_seq_hi_res",
122 | // 8 bits for "clk_seq_low",
123 | // two most significant bits holds zero and one for variant DCE1.1
124 | mt_rand(0, 0x3fff) | 0x8000,
125 |
126 | // 48 bits for "node"
127 | mt_rand(0, 0xffff),
128 | mt_rand(0, 0xffff),
129 | mt_rand(0, 0xffff)
130 | );
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
Total de líneas: 133
================================================================================
================================================================================
ARCHIVO #105: src/Core/System.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Core/System.php
Tamaño: 2.99 KB
--------------------------------------------------------------------------------
1 | TableName = $Definition->Table;
32 | $this->Schema = $Definition->Schema;
33 |
34 | foreach ($Definition->Properties as $item) {
35 |
36 | if ($item instanceof PropertyDefinition) {
37 | $name = $item->Name;
38 | $oldValue = (isset($this->CurrentEntity)) ? $this->CurrentEntity->$name : null;
39 | $newValue = (isset($this->NewEntity)) ? $this->NewEntity->$name : null;
40 |
41 | if ($item->IsAuditable) {
42 | $displayFormat = "";
43 | $currentValueFormated = "";
44 | $newValueFormated = "";
45 |
46 | if (isset($item->DisplayFormat) && $item->DisplayFormat instanceof Format) {
47 | $displayFormat = $item->DisplayFormat->Type;
48 | $currentValueFormated = $this->FormatValue($item->DisplayFormat, $oldValue);
49 | $newValueFormated = $this->FormatValue($item->DisplayFormat, $newValue);
50 | }
51 |
52 | $this->AuditableFields[] = new AuditField(
53 | FieldName: $item->Name,
54 | IsKey: $item->IsKey,
55 | ColumnName: $item->ColumnName,
56 | ColumnType: $item->ColumnType,
57 | IsNullable: $item->IsNullable,
58 | Display: $item->Display,
59 | DisplayFormat: $displayFormat,
60 | CurrentValue: $oldValue,
61 | CurrentValueFormated: $currentValueFormated,
62 | NewValue: $newValue,
63 | NewValueFormated: $newValueFormated,
64 | );
65 | }
66 | }
67 | }
68 | }
69 |
70 | public function Run()
71 | {
72 |
73 | // Inicializamos
74 | //
75 | $this->Auditable->GuardarAuditoria($this);
76 |
77 | // Ok, obtener el objeto si es un update, para cargar
78 | // los valores previos
79 | }
80 |
81 | private function FormatValue(Format $formato, $value)
82 | {
83 | $result = "";
84 | switch ($formato->Type) {
85 | case FormatTypeEnum::MONEY:
86 | $result = _mon($value, $formato->Decimals);
87 | break;
88 | case FormatTypeEnum::INTEGER:
89 | $result = _num($value);
90 | break;
91 | case FormatTypeEnum::DECIMAL:
92 | $result = _dec($value, $formato->Decimals);
93 | break;
94 | case FormatTypeEnum::DATE:
95 | $formatDate = "d-m-Y";
96 | if (isset($formato->FromatString) && $formato->FromatString != "")
97 | $formatDate = $formato->FromatString;
98 | if (isset($value) && $value != "")
99 | $result = (new Date($value))->format($formatDate);
100 | break;
101 | case FormatTypeEnum::DATETIME:
102 | $formatDate = "d-m-Y H:i:s";
103 | if (isset($formato->FromatString) && $formato->FromatString != "")
104 | $formatDate = $formato->FromatString;
105 | if (isset($value) && $value != "")
106 | $result = (new Date($value))->format($formatDate);
107 | break;
108 | default:
109 | break;
110 | }
111 | return $result;
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
Total de líneas: 114
================================================================================
================================================================================
ARCHIVO #108: src/Dao/BasicDao.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Dao/BasicDao.php
Tamaño: 31.77 KB
--------------------------------------------------------------------------------
1 | 0) {
33 | self::$GlobalTop = $top;
34 | }
35 | }
36 |
37 | public function GetEntityName()
38 | {
39 | return $this->EntityDefinition->Entity;
40 | }
41 |
42 | function __construct($entity, $domain)
43 | {
44 |
45 | // Obtener la información de la entidad
46 | //$this->EntityDefinition = EntityDefinition::GetInstance(new \ReflectionClass($entity));
47 | $this->EntityDefinition = EntityDefinition::Instance($entity); // << version con control de caché y almacenamiento en redis
48 |
49 | // Asignar el dominio para el acceso a datos
50 | // Buscar el dominio
51 | $dominios = ConnectionConfig::Instance();
52 |
53 | $this->Domain = $dominios[$domain];
54 | //$this->Domain = $domain;
55 |
56 | // Obtener una instancia de conexión PDO para utilizar
57 | // con este DAO
58 | if ($this->Connection === null) {
59 | $this->Connection = DataConfig::GetPDOConnection($domain);
60 | }
61 | }
62 |
63 | public function Query(Queryable $query, bool $returnFirstRecord = false, $transaction = null, $nosanear = false)
64 | {
65 |
66 | $qry = $query->Build();
67 | if (!isset($transaction)) {
68 | $transaction = $this->Connection;
69 | }
70 |
71 | $stmt = $transaction->prepare($qry->Statement);
72 |
73 | foreach ($qry->Bindings as $binding) {
74 |
75 | $param = FALSE;
76 |
77 | if (is_int($binding->BindingValue))
78 | $param = PDO::PARAM_INT;
79 | else if (is_bool($binding->BindingValue))
80 | $param = PDO::PARAM_BOOL;
81 | else if (is_null($binding->BindingValue))
82 | $param = PDO::PARAM_NULL;
83 | else if (is_string($binding->BindingValue))
84 | $param = PDO::PARAM_STR;
85 | else
86 | $param = PDO::PARAM_STR;
87 |
88 | if ($param)
89 | $stmt->bindValue($binding->BindingVariable, $binding->BindingValue, $param);
90 | }
91 |
92 | $results = new GenericCollection(
93 | Key: $qry->FromDefinition->Key,
94 | Values: $this->ExecuteStatementForQueryable($stmt),
95 | DtoName: $qry->FromDefinition->Entity
96 | );
97 |
98 | // FROM results
99 | $fromKey = $qry->FromDefinition->Key;
100 |
101 | // Obtener el DISTINCT de la tabla padre
102 | $parentDistinct = $results->DistinctItem($fromKey)->Values;
103 | $parentEntities = Mapper::ToEntities($parentDistinct, $qry->FromDefinition->Entity, '', true, $nosanear);
104 |
105 | $fromResults = new GenericCollection(
106 | Key: $qry->FromDefinition->Key,
107 | Values: $parentEntities,
108 | DtoName: $qry->FromDefinition->Entity
109 | );
110 |
111 | // JOIN results
112 | foreach ($qry->JoinDefinitions as $joinDefinition) {
113 | $joinKey = $joinDefinition->TablePrefix . '.' . $joinDefinition->Key;
114 |
115 | $distincts = $results->DistinctItem($joinKey);
116 |
117 | $joinResults = new GenericCollection(
118 | Key: $joinDefinition->Key,
119 | Values: Mapper::ToEntities(
120 | $distincts,
121 | $joinDefinition->Entity,
122 | $joinDefinition->TablePrefix,
123 | true,
124 | $nosanear
125 | ),
126 | DtoName: $joinDefinition->Entity
127 | );
128 |
129 | // Incorporarlo al resultado principal como JOIN
130 | $fromResults->MergeChildren(
131 | new MergeDefinition(
132 | Values: $joinResults,
133 | ParentKey: (isset($joinDefinition->CustomParentKey) && $joinDefinition->CustomParentKey != '') ? $joinDefinition->CustomParentKey : $qry->FromDefinition->Key,
134 | ChildReferenceKey: (isset($joinDefinition->CustomForeignKey) && $joinDefinition->CustomForeignKey != '') ? $joinDefinition->CustomForeignKey : $qry->FromDefinition->Key
135 | )
136 | );
137 | }
138 |
139 | // LEFT JOIN results
140 | foreach ($qry->LeftJoinDefinitions as $joinDefinition) {
141 | $joinKey = $joinDefinition->TablePrefix . '.' . $joinDefinition->Key;
142 | $joinResults = new GenericCollection(
143 | Key: $joinDefinition->Key,
144 | Values: Mapper::ToEntities(
145 | $results->DistinctItem($joinKey),
146 | $joinDefinition->Entity,
147 | $joinDefinition->TablePrefix,
148 | true,
149 | $nosanear
150 | ),
151 | DtoName: $joinDefinition->Entity
152 | );
153 |
154 | // Incorporarlo al resultado principal como JOIN
155 | $fromResults->MergeChildren(
156 | new MergeDefinition(
157 | Values: $joinResults,
158 | ParentKey: (isset($joinDefinition->CustomParentKey) && $joinDefinition->CustomParentKey != '') ? $joinDefinition->CustomParentKey : $qry->FromDefinition->Key,
159 | ChildReferenceKey: (isset($joinDefinition->CustomForeignKey) && $joinDefinition->CustomForeignKey != '') ? $joinDefinition->CustomForeignKey : $qry->FromDefinition->Key
160 | )
161 | );
162 | }
163 |
164 | // WITH results
165 | foreach ($qry->WithDefinitions as $withDefinition) {
166 | $withKey = $withDefinition->TablePrefix . '.' . $withDefinition->Key;
167 | $withResults = new GenericCollection(
168 | Values: Mapper::ToEntities(
169 | $results->DistinctItem($withKey),
170 | $withDefinition->Entity,
171 | $withDefinition->TablePrefix,
172 | true,
173 | $nosanear
174 | ),
175 | DtoName: $withDefinition->Entity
176 | );
177 |
178 | $fromResults->Attach(
179 | new AttachDefinition(
180 | Values: $withResults,
181 | AttachPrimaryKey: (isset($withDefinition->CustomParentKey) && $withDefinition->CustomParentKey != '') ? $withDefinition->CustomParentKey : $withDefinition->Key,
182 | ForeignKey: (isset($withDefinition->CustomForeignKey) && $withDefinition->CustomForeignKey != '') ? $withDefinition->CustomForeignKey : $withDefinition->Key
183 | )
184 | );
185 | }
186 |
187 | if ($returnFirstRecord) {
188 | if (isset($fromResults) && $fromResults->Count() > 0) {
189 | return $fromResults->First();
190 | } else {
191 | return null;
192 | }
193 | } else {
194 | return $fromResults->Values;
195 | }
196 | }
197 |
198 | public function Find($keyValue, $incluirNoVigentes = true, $incluirEliminados = true, $transaction = null)
199 | {
200 | if ($incluirNoVigentes && $incluirEliminados) {
201 | $where = "";
202 | } else {
203 | if (!$incluirNoVigentes) {
204 | $where = "
205 | AND IndVigente = 1";
206 | }
207 | if (!$incluirEliminados) {
208 | $where = "
209 | AND IndEliminado = 0";
210 | }
211 | }
212 |
213 | if (!isset($transaction)) {
214 | $transaction = $this->Connection;
215 | }
216 |
217 | $stmt = $transaction->prepare('
218 | SELECT ' . $this->EntityDefinition->NotIgnoredFields . '
219 | FROM ' . $this->EntityDefinition->Table . '
220 | WHERE ' . $this->EntityDefinition->Key . ' = :keyValue' . '
221 | ' . $where);
222 |
223 | $stmt->bindParam(':keyValue', $keyValue);
224 |
225 | return $this->ExecuteStatementForObject($stmt);
226 | }
227 |
228 | public function FindByForeign($foreignKey, $foreignKeyValue, $transaction = null)
229 | {
230 |
231 | $foreignKeyBind = ':' . $foreignKey;
232 |
233 | $qry = '
234 | SELECT ' . $this->EntityDefinition->NotIgnoredFields . '
235 | FROM ' . $this->EntityDefinition->Table . '
236 | WHERE ' . $foreignKey . ' = ' . $foreignKeyBind;
237 |
238 | if (!isset($transaction)) {
239 | $transaction = $this->Connection;
240 | }
241 |
242 | $stmt = $transaction->prepare($qry);
243 |
244 | $stmt->bindValue("$foreignKeyBind", $foreignKeyValue);
245 |
246 | return $this->ExecuteStatementForObject($stmt);
247 | }
248 |
249 | function GetByCodigoRegistro($codigoRegistro, $transaction = null)
250 | {
251 | if (!isset($transaction)) {
252 | $transaction = $this->Connection;
253 | }
254 |
255 | $stmt = $transaction->prepare("
256 | SELECT
257 | " . $this->EntityDefinition->NotIgnoredFields . "
258 | FROM " . $this->EntityDefinition->Table . "
259 | WHERE CodigoRegistro = :keyValue
260 | ");
261 |
262 | $stmt->bindParam(':keyValue', $codigoRegistro);
263 |
264 | return $this->ExecuteStatementForObjects($stmt);
265 | }
266 |
267 | public function GetByForeign($foreignKey, $foreignKeyValue, $orderFields = '', $transaction = null)
268 | {
269 |
270 | $foreignKeyBind = ':' . $foreignKey;
271 |
272 | $qry = '
273 | SELECT ' . $this->EntityDefinition->NotIgnoredFields . '
274 | FROM ' . $this->EntityDefinition->Table . '
275 | WHERE ' . $foreignKey . ' = ' . $foreignKeyBind;
276 |
277 | if ($orderFields != '') {
278 | $qry .= ' ORDER BY ' . $orderFields;
279 | }
280 |
281 | if (!isset($transaction)) {
282 | $transaction = $this->Connection;
283 | }
284 |
285 | $stmt = $transaction->prepare($qry);
286 |
287 | $stmt->bindValue("$foreignKeyBind", $foreignKeyValue);
288 |
289 | return $this->ExecuteStatementForObjects($stmt);
290 | }
291 |
292 |
293 | public function GetByToFile($bindings, $orderFields = '', $top = 0, $transaction = null, $localDataFolder = "") {
294 | if ($top == 0) {
295 | if (isset(self::$GlobalTop) && self::$GlobalTop > 0) {
296 | $top = self::$GlobalTop;
297 | }
298 | }
299 |
300 | $select = "SELECT ";
301 |
302 | if ($this->Domain->Type == 'sqlserver' && is_numeric($top) && $top > 0) {
303 | $select .= 'TOP ' . $top . ' ';
304 | }
305 |
306 | $qry = $select . $this->EntityDefinition->NotIgnoredFields . ' FROM ' . $this->EntityDefinition->Table;
307 |
308 | /* @var $var BindVariable */
309 | $count = 0;
310 | $where = '';
311 | $bind = array();
312 |
313 | if ($bindings instanceof BindVariable) {
314 | $bindings = [$bindings];
315 | }
316 |
317 | foreach ($bindings as $key => $var) {
318 |
319 | if ($count > 0) {
320 | $where .= '
321 | AND
322 | ';
323 | }
324 |
325 | if (strtoupper($var->Operator) == 'LIKE') {
326 |
327 | // Ver si es campo fecha
328 | if ($this->Domain->Type == "sqlserver") {
329 | $where .= $var->Field . " LIKE :var" . $count . " ";
330 | } else if ($this->Domain->Type == "mysql") {
331 | $where .= $var->Field . " LIKE :var" . $count . " ";
332 | } else {
333 | $where .= $var->Field . " LIKE :var" . $count . " ";
334 | }
335 |
336 | $bind['var' . $count] = $var->Operand1;
337 | $count++;
338 | } else if (strtoupper($var->Operator) == 'BETWEEN') {
339 |
340 | // Ver si es campo fecha
341 | if (
342 | $this->Domain->Type == "sqlserver"
343 | && isset($this->EntityDefinition->Properties[$var->Field])
344 | && $this->EntityDefinition->Properties[$var->Field]->ColumnType == 'datetime'
345 | ) {
346 | $where .= $var->Field . ' BETWEEN CONVERT(DATETIME, :var' . $count . ', 121) AND CONVERT(DATETIME, :var' . ($count + 1) . ', 121) ';
347 | } else {
348 | $where .= $var->Field . ' BETWEEN :var' . $count . ' AND :var' . ($count + 1) . ' ';
349 | }
350 |
351 |
352 |
353 | $bind['var' . $count] = $var->Operand1;
354 | $count++;
355 | $bind['var' . $count] = $var->Operand2;
356 |
357 | $count++;
358 | } else if (strtoupper($var->Operator) == 'IN' && is_array($var->Operand1)) {
359 |
360 | $variables = '';
361 | foreach ($var->Operand1 as $op) {
362 | if ($variables != '')
363 | $variables .= ', ';
364 | $variables .= ':var' . $count;
365 | $bind['var' . $count] = $op;
366 | $count++;
367 | }
368 |
369 | $where .= $var->Field . ' ' . $var->Operator . ' (' . $variables . ') ';
370 | } else {
371 |
372 | if (
373 | $this->Domain->Type == "sqlserver"
374 | && isset($this->EntityDefinition->Properties[$var->Field])
375 | && $this->EntityDefinition->Properties[$var->Field]->ColumnType == 'datetime'
376 | ) {
377 | $where .= $var->Field . ' ' . $var->Operator . ' CONVERT(DATETIME, :var' . $count . ', 121) ';
378 | } else {
379 | $where .= $var->Field . ' ' . $var->Operator . ' :var' . $count . ' ';
380 | }
381 |
382 |
383 | $bind['var' . $count] = $var->Operand1;
384 |
385 | $count++;
386 | }
387 | }
388 |
389 | if ($where != '') {
390 | $qry .= ' WHERE ' . $where;
391 | }
392 |
393 | if ($orderFields != '') {
394 | $qry .= ' ORDER BY ' . $orderFields;
395 | }
396 |
397 | if (!isset($transaction)) {
398 | $transaction = $this->Connection;
399 | }
400 |
401 | // preparar sentencia
402 | $stmt = $transaction->prepare($qry);
403 |
404 | // ligar variables
405 | foreach ($bind as $v => $value) {
406 | //echo "...binding :" . $v . " with value [" . $value . "]
";
407 | if (is_int($value))
408 | $param = PDO::PARAM_INT;
409 | elseif (is_bool($value))
410 | $param = PDO::PARAM_BOOL;
411 | elseif (is_null($value))
412 | $param = PDO::PARAM_NULL;
413 | elseif (is_string($value))
414 | $param = PDO::PARAM_STR;
415 | else
416 | $param = FALSE;
417 |
418 | if ($param)
419 | $stmt->bindValue(":$v", $value, $param);
420 | }
421 |
422 | return $this->ExecuteStatementToFile($stmt, null, $localDataFolder);
423 | }
424 |
425 | public function GetBy($bindings, $orderFields = '', $top = 0, $transaction = null)
426 | {
427 | if ($top == 0) {
428 | if (isset(self::$GlobalTop) && self::$GlobalTop > 0) {
429 | $top = self::$GlobalTop;
430 | }
431 | }
432 |
433 | $select = "SELECT ";
434 |
435 | if ($this->Domain->Type == 'sqlserver' && is_numeric($top) && $top > 0) {
436 | $select .= 'TOP ' . $top . ' ';
437 | }
438 |
439 | $qry = $select . $this->EntityDefinition->NotIgnoredFields . ' FROM ' . $this->EntityDefinition->Table;
440 |
441 | /* @var $var BindVariable */
442 | $count = 0;
443 | $where = '';
444 | $bind = array();
445 |
446 | if ($bindings instanceof BindVariable) {
447 | $bindings = [$bindings];
448 | }
449 |
450 | foreach ($bindings as $key => $var) {
451 |
452 | if ($count > 0) {
453 | $where .= '
454 | AND
455 | ';
456 | }
457 |
458 | if (strtoupper($var->Operator) == 'LIKE') {
459 |
460 | // Ver si es campo fecha
461 | if ($this->Domain->Type == "sqlserver") {
462 | $where .= $var->Field . " LIKE :var" . $count . " ";
463 | } else if ($this->Domain->Type == "mysql") {
464 | $where .= $var->Field . " LIKE :var" . $count . " ";
465 | } else {
466 | $where .= $var->Field . " LIKE :var" . $count . " ";
467 | }
468 |
469 | $bind['var' . $count] = $var->Operand1;
470 | $count++;
471 | } else if (strtoupper($var->Operator) == 'BETWEEN') {
472 |
473 | // Ver si es campo fecha
474 | if (
475 | $this->Domain->Type == "sqlserver"
476 | && isset($this->EntityDefinition->Properties[$var->Field])
477 | && $this->EntityDefinition->Properties[$var->Field]->ColumnType == 'datetime'
478 | ) {
479 | $where .= $var->Field . ' BETWEEN CONVERT(DATETIME, :var' . $count . ', 121) AND CONVERT(DATETIME, :var' . ($count + 1) . ', 121) ';
480 | } else {
481 | $where .= $var->Field . ' BETWEEN :var' . $count . ' AND :var' . ($count + 1) . ' ';
482 | }
483 |
484 |
485 |
486 | $bind['var' . $count] = $var->Operand1;
487 | $count++;
488 | $bind['var' . $count] = $var->Operand2;
489 |
490 | $count++;
491 | } else if (strtoupper($var->Operator) == 'IN' && is_array($var->Operand1)) {
492 |
493 | $variables = '';
494 | foreach ($var->Operand1 as $op) {
495 | if ($variables != '')
496 | $variables .= ', ';
497 | $variables .= ':var' . $count;
498 | $bind['var' . $count] = $op;
499 | $count++;
500 | }
501 |
502 | $where .= $var->Field . ' ' . $var->Operator . ' (' . $variables . ') ';
503 | } else {
504 |
505 | if (
506 | $this->Domain->Type == "sqlserver"
507 | && isset($this->EntityDefinition->Properties[$var->Field])
508 | && $this->EntityDefinition->Properties[$var->Field]->ColumnType == 'datetime'
509 | ) {
510 | $where .= $var->Field . ' ' . $var->Operator . ' CONVERT(DATETIME, :var' . $count . ', 121) ';
511 | } else {
512 | $where .= $var->Field . ' ' . $var->Operator . ' :var' . $count . ' ';
513 | }
514 |
515 |
516 | $bind['var' . $count] = $var->Operand1;
517 |
518 | $count++;
519 | }
520 | }
521 |
522 | if ($where != '') {
523 | $qry .= ' WHERE ' . $where;
524 | }
525 |
526 | if ($orderFields != '') {
527 | $qry .= ' ORDER BY ' . $orderFields;
528 | }
529 |
530 | if (!isset($transaction)) {
531 | $transaction = $this->Connection;
532 | }
533 |
534 | // preparar sentencia
535 | $stmt = $transaction->prepare($qry);
536 |
537 | // ligar variables
538 | foreach ($bind as $v => $value) {
539 | //echo "...binding :" . $v . " with value [" . $value . "]
";
540 | if (is_int($value))
541 | $param = PDO::PARAM_INT;
542 | elseif (is_bool($value))
543 | $param = PDO::PARAM_BOOL;
544 | elseif (is_null($value))
545 | $param = PDO::PARAM_NULL;
546 | elseif (is_string($value))
547 | $param = PDO::PARAM_STR;
548 | else
549 | $param = FALSE;
550 |
551 | if ($param)
552 | $stmt->bindValue(":$v", $value, $param);
553 | }
554 |
555 | $result = $this->ExecuteStatementForObjects($stmt);
556 |
557 | return $result;
558 | }
559 |
560 | public function FindBy($bindings, $orderFields = '', $transaction = null)
561 | {
562 | $select = "SELECT ";
563 |
564 | if ($this->Domain->Type == 'sqlserver') {
565 | $select .= 'TOP 1 ';
566 | }
567 | $qry = $select . $this->EntityDefinition->NotIgnoredFields . ' FROM ' . $this->EntityDefinition->Table;
568 |
569 | /* @var $var BindVariable */
570 | $count = 0;
571 | $where = '';
572 | $bind = array();
573 | foreach ($bindings as $key => $var) {
574 |
575 | if ($count > 0) {
576 | $where .= '
577 | AND
578 | ';
579 | }
580 |
581 | if ($var->Operator == 'BETWEEN') {
582 | $where .= $var->Field . ' BETWEEN :var' . $count . ' AND :var' . ($count + 1) . ' ';
583 |
584 | $bind['var' . $count] = $var->Operand1;
585 | $count++;
586 | $bind['var' . $count] = $var->Operand2;
587 | } else if (strtoupper($var->Operator) == 'IN' && is_array($var->Operand1)) {
588 |
589 | $variables = '';
590 | foreach ($var->Operand1 as $op) {
591 | if ($variables == '')
592 | $variables .= ', ';
593 | $variables .= ':var' . $count;
594 | $bind['var' . $count] = $op;
595 | $count++;
596 | }
597 |
598 | $where .= $var->Field . ' ' . $var->Operator . $variables . ' ';
599 | } else {
600 |
601 | if (
602 | $this->Domain->Type == "sqlserver"
603 | && isset($this->EntityDefinition->Properties[$var->Field])
604 | && $this->EntityDefinition->Properties[$var->Field]->ColumnType == 'datetime'
605 | ) {
606 | $where .= $var->Field . ' ' . $var->Operator . ' CONVERT(DATETIME, :var' . $count . ', 121) ';
607 | } else {
608 | $where .= $var->Field . ' ' . $var->Operator . ' :var' . $count . ' ';
609 | }
610 |
611 | //$where .= $var->Field . ' ' . $var->Operator . ' :var' . $count . ' ';
612 | $bind['var' . $count] = $var->Operand1;
613 | }
614 |
615 | $count++;
616 | }
617 |
618 | if ($where != '') {
619 | $qry .= ' WHERE ' . $where;
620 | }
621 |
622 | if ($this->Domain->Type == 'oracle') {
623 | if ($where == '') {
624 | $where = ' WHERE ROWNUM <= 1';
625 | } else {
626 | $where .= ' AND ROWNUM <= 1';
627 | }
628 | }
629 |
630 | if ($orderFields != '') {
631 | $qry .= ' ORDER BY ' . $orderFields;
632 | }
633 |
634 | if ($this->Domain->Type == 'mysql')
635 | $qry .= ' LIMIT 1';
636 |
637 | if (!isset($transaction)) {
638 | $transaction = $this->Connection;
639 | }
640 | // preparar sentencia
641 | $stmt = $transaction->prepare($qry);
642 |
643 | // ligar variables
644 | foreach ($bind as $v => $value) {
645 | //echo "...binding :" . $v . " with value [" . $value . "]
";
646 | if (is_int($value))
647 | $param = PDO::PARAM_INT;
648 | elseif (is_bool($value))
649 | $param = PDO::PARAM_BOOL;
650 | elseif (is_null($value))
651 | $param = PDO::PARAM_NULL;
652 | elseif (is_string($value))
653 | $param = PDO::PARAM_STR;
654 | else
655 | $param = FALSE;
656 |
657 | if ($param)
658 | $stmt->bindValue(":$v", $value, $param);
659 | }
660 |
661 | return $this->ExecuteStatementForObject($stmt);
662 | }
663 |
664 | public function GetAll($order = "", $transaction = null)
665 | {
666 | $qry = 'SELECT ' . $this->EntityDefinition->NotIgnoredFields . ' FROM ' . $this->EntityDefinition->Table . (($order != '') ? ' ORDER BY ' . $order : '');
667 |
668 | if (!isset($transaction)) {
669 | $transaction = $this->Connection;
670 | }
671 |
672 | $stmt = $transaction->prepare($qry);
673 |
674 | return $this->ExecuteStatementForObjects($stmt);
675 | }
676 |
677 | public function GetByStmt($stmt)
678 | {
679 | return $this->ExecuteStatementForObjects($stmt);
680 | }
681 |
682 | public function FindByStmt($stmt)
683 | {
684 | return $this->ExecuteStatementForObject($stmt);
685 | }
686 |
687 | public function GetStatementFromFile($filePath)
688 | {
689 | // Abrir el archivo y retornar la query
690 | if (\file_exists(__DIR__ . '/' . $filePath)) {
691 | return \file_get_contents(__DIR__ . '/' . $filePath);
692 | } else {
693 | throw new \Exception("Archivo no existe");
694 | }
695 | }
696 |
697 | function SumFieldByForeign($fieldName, $foreignKeyName, $foreignKeyValue, $transaction = null)
698 | {
699 |
700 | if (!isset($transaction)) {
701 | $transaction = $this->Connection;
702 | }
703 |
704 | $stmt = $transaction->prepare('
705 | SELECT SUM(' . $fieldName . ') AS SUMRESULT
706 | FROM ' . $this->EntityDefinition->Table . '
707 | WHERE ' . $foreignKeyName . ' = :foreignKeyValue
708 | ');
709 |
710 | $stmt->bindParam(':foreignKeyValue', $foreignKeyValue);
711 | return $this->ExecuteScalar($stmt);
712 | }
713 |
714 | function CountByForeign($foreignKeyName, $foreignKeyValue, $transaction = null)
715 | {
716 | if (!isset($transaction)) {
717 | $transaction = $this->Connection;
718 | }
719 |
720 | $stmt = $transaction->prepare('
721 | SELECT COUNT(1) AS COUNTRESULT
722 | FROM ' . $this->EntityDefinition->Table . '
723 | WHERE ' . $foreignKeyName . ' = :foreignKeyValue
724 | ');
725 |
726 | $stmt->bindParam(':foreignKeyValue', $foreignKeyValue);
727 | return $this->ExecuteScalar($stmt);
728 | }
729 |
730 | function Count($transaction = null)
731 | {
732 | if (!isset($transaction)) {
733 | $transaction = $this->Connection;
734 | }
735 |
736 | $stmt = $transaction->prepare('
737 | SELECT COUNT(1) AS COUNTRESULT
738 | FROM ' . $this->EntityDefinition->Table);
739 |
740 | return $this->ExecuteScalar($stmt);
741 | }
742 |
743 | public function CountBy($bindings, $transaction = null)
744 | {
745 | $qry = 'SELECT COUNT(1) AS COUNTRESULT FROM ' . $this->EntityDefinition->Table;
746 |
747 | /* @var $var BindVariable */
748 | $count = 0;
749 | $where = '';
750 | $bind = array();
751 | foreach ($bindings as $key => $var) {
752 |
753 | if ($count > 0) {
754 | $where .= '
755 | AND
756 | ';
757 | }
758 |
759 | if ($var->Operator == 'BETWEEN') {
760 | $where .= $var->Field . ' BETWEEN :var' . $count . ' AND :var' . ($count + 1) . ' ';
761 |
762 | $bind['var' . $count] = $var->Operand1;
763 | $count++;
764 | $bind['var' . $count] = $var->Operand2;
765 | } else if (strtoupper($var->Operator) == 'IN' && is_array($var->Operand1)) {
766 |
767 | $variables = '';
768 | foreach ($var->Operand1 as $op) {
769 | if ($variables != '')
770 | $variables .= ', ';
771 | $variables .= ':var' . $count;
772 | $bind['var' . $count] = $op;
773 | $count++;
774 | }
775 |
776 | $where .= $var->Field . ' ' . $var->Operator . ' (' . $variables . ') ';
777 | } else {
778 | $where .= $var->Field . ' ' . $var->Operator . ' :var' . $count . ' ';
779 | $bind['var' . $count] = $var->Operand1;
780 | }
781 |
782 | $count++;
783 | }
784 |
785 | if ($where != '') {
786 | $qry .= ' WHERE ' . $where;
787 | }
788 |
789 | if (!isset($transaction)) {
790 | $transaction = $this->Connection;
791 | }
792 | // preparar sentencia
793 | $stmt = $transaction->prepare($qry);
794 |
795 | // ligar variables
796 | foreach ($bind as $v => $value) {
797 | //echo "...binding :" . $v . " with value [" . $value . "]
";
798 | if (is_int($value))
799 | $param = PDO::PARAM_INT;
800 | elseif (is_bool($value))
801 | $param = PDO::PARAM_BOOL;
802 | elseif (is_null($value))
803 | $param = PDO::PARAM_NULL;
804 | elseif (is_string($value))
805 | $param = PDO::PARAM_STR;
806 | else
807 | $param = FALSE;
808 |
809 | if ($param)
810 | $stmt->bindValue(":$v", $value, $param);
811 | }
812 |
813 | return $this->ExecuteScalar($stmt);
814 | }
815 |
816 | public function GetIN($foreignKey, $foreignKeyValue, $orderFields = '', $transaction = null)
817 | {
818 | // Se genera un campo vacio para cargar los KeyValues
819 | $values = '';
820 |
821 | //Verifico que KeyValue se un arreglo
822 | if (is_array($foreignKeyValue) or is_object($foreignKeyValue)):
823 | //Si es numerico uso la función Implode para convertir el Arreglo en String
824 | if (is_numeric($foreignKeyValue[0])):
825 | $values = implode(', ', $foreignKeyValue);
826 | else:
827 | //Si no es un Arreglo Calculco el total de valores pasados
828 |
829 | $t = count($foreignKeyValue) - 1;
830 |
831 | //Recorro los valores y los incorporo a la variable Values
832 | foreach ($foreignKeyValue as $k => $vl) {
833 |
834 | //Si la Llave ES IGUAL al total de registros no se agrega una coma al final
835 | if ($k == $t) {
836 | $values .= "'" . $vl . "'";
837 | } else {
838 | $values .= "'" . $vl . "' , ";
839 | }
840 | }
841 |
842 | endif;
843 | else:
844 | $values = $foreignKeyValue;
845 | endif;
846 |
847 | //Se define los arreglos
848 | $qry = '
849 | SELECT ' . $this->EntityDefinition->NotIgnoredFields . '
850 | FROM ' . $this->EntityDefinition->Table . '
851 | WHERE ' . $foreignKey . ' IN (' . $values . ')';
852 |
853 |
854 | if ($orderFields != '') {
855 | $qry .= ' ORDER BY ' . $orderFields;
856 | }
857 |
858 | if (!isset($transaction)) {
859 | $transaction = $this->Connection;
860 | }
861 |
862 | $stmt = $transaction->prepare($qry);
863 |
864 | return $this->ExecuteStatementForObjects($stmt);
865 | }
866 |
867 | function Max($field, $ignoreBlanks = false, $transaction = null)
868 | {
869 |
870 | $qry = 'SELECT Max(' . $field . ') AS MAXRESULT FROM ' . $this->EntityDefinition->Table;
871 |
872 | if ($ignoreBlanks) {
873 | $qry .= " WHERE " . $field . " IS NOT NULL AND " . $field . " <> ''";
874 | }
875 |
876 | if (!isset($transaction)) {
877 | $transaction = $this->Connection;
878 | }
879 |
880 | $stmt = $transaction->prepare($qry);
881 | return $this->ExecuteScalar($stmt);
882 | }
883 |
884 | function Min($field, $ignoreBlanks = false, $transaction = null)
885 | {
886 |
887 | $qry = 'SELECT Min(' . $field . ') AS MINRESULT FROM ' . $this->EntityDefinition->Table;
888 |
889 | if ($ignoreBlanks) {
890 | $qry .= " WHERE " . $field . " IS NOT NULL AND " . $field . " <> ''";
891 | }
892 |
893 | if (!isset($transaction)) {
894 | $transaction = $this->Connection;
895 | }
896 |
897 | $stmt = $transaction->prepare($qry);
898 | return $this->ExecuteScalar($stmt);
899 | }
900 | }
901 | }
902 |
--------------------------------------------------------------------------------
Total de líneas: 902
================================================================================
================================================================================
ARCHIVO #109: src/Dao/BindVariable.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Dao/BindVariable.php
Tamaño: 2.32 KB
--------------------------------------------------------------------------------
1 | Field = $field;
21 | $this->Operator = $operator;
22 | $this->Operand1 = $operand1;
23 | $this->Operand2 = $operand2;
24 | }
25 |
26 | /**
27 | * Crea una condición predefinida para filtrar registros activos.
28 | *
29 | * Retorna una instancia de BindVariable con el campo `IndActivo` igual a 1
30 | *
31 | * @return BindVariable Condición para registros activos (IndActivo = 1).
32 | */
33 | public static function Activo() {
34 | return new BindVariable('IndActivo', '=', 1);
35 | }
36 |
37 | /**
38 | * Crea una condición predefinida para filtrar registros eliminados.
39 | *
40 | * Retorna una instancia de BindVariable con el campo `IndEliminado` igual a 1
41 | *
42 | * @return BindVariable Condición para registros eliminados (IndEliminado = 1).
43 | */
44 | public static function Eliminado() {
45 | return new BindVariable('IndEliminado', '=', 1);
46 | }
47 |
48 | /**
49 | * Crea una condición predefinida para filtrar registros NO activos.
50 | *
51 | * Retorna una instancia de BindVariable con el campo `IndActivo` igual a 0
52 | *
53 | * @return BindVariable Condición para registros NO activos (IndActivo = 0).
54 | */
55 | public static function NoActivo() {
56 | return new BindVariable('IndActivo', '=', 0);
57 | }
58 |
59 | /**
60 | * Crea una condición predefinida para filtrar registros NO eliminados.
61 | *
62 | * Retorna una instancia de BindVariable con el campo `IndEliminado` igual a 0
63 | *
64 | * @return BindVariable Condición para registros NO eliminados (IndEliminado = 0).
65 | */
66 | public static function NoEliminado() {
67 | return new BindVariable('IndEliminado', '=', 0);
68 | }
69 | }
70 |
71 | }
--------------------------------------------------------------------------------
Total de líneas: 71
================================================================================
================================================================================
ARCHIVO #110: src/Dao/ConnectionTypeEnum.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Dao/ConnectionTypeEnum.php
Tamaño: 411 bytes
--------------------------------------------------------------------------------
1 | Type == 'mysql') {
36 | $conn = new PDO(
37 | "mysql:dbname=" . $dom->Database . ";host=" . $dom->Host . ":" . $dom->Port . ";charset=utf8",
38 | $dom->User,
39 | $dom->Password,
40 | array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'")
41 | );
42 | $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
43 |
44 | return $conn;
45 | } else if ($dom->Type == 'sqlserver') {
46 | if ($transactionLevel != null) {
47 | $conn = new PDO(
48 | "sqlsrv:Server=" . $dom->Host . "," . $dom->Port . ";Database=" . $dom->Database . ";Encrypt=true;TrustServerCertificate=true;TransactionIsolation=" . $transactionLevel,
49 | $dom->User,
50 | $dom->Password
51 | );
52 | } else {
53 | $conn = new PDO(
54 | "sqlsrv:Server=" . $dom->Host . "," . $dom->Port . ";Database=" . $dom->Database . ';Encrypt=true;TrustServerCertificate=true',
55 | $dom->User,
56 | $dom->Password
57 | );
58 | }
59 |
60 | $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
61 | return $conn;
62 | } else {
63 | return null;
64 | }
65 | } else {
66 | return null;
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
Total de líneas: 70
================================================================================
================================================================================
ARCHIVO #112: src/Dao/DefinitionTypeEnum.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Dao/DefinitionTypeEnum.php
Tamaño: 453 bytes
--------------------------------------------------------------------------------
1 | getDocComment();
18 | return self::GetAnnotationsFromDocumentation($classdoc);
19 |
20 | }
21 |
22 | public static function GetPropertyAnnotations(\ReflectionProperty $property, $annotationSeparator = ",") {
23 |
24 | $propdoc = $property->getDocComment();
25 | return self::GetAnnotationsFromDocumentation($propdoc, $annotationSeparator);
26 |
27 | }
28 |
29 | private static function GetAnnotationsFromDocumentation($propdoc, $annotationSeparator = ",") {
30 |
31 | // Remover los delimitadores
32 | $propdoc = str_replace('/**', '', $propdoc);
33 | $propdoc = str_replace('*/', '', $propdoc);
34 | $propdoc = str_replace("\n *", "\n", $propdoc);
35 |
36 | // Los bloques deben estar separados por comas
37 | $bloques = explode($annotationSeparator, $propdoc);
38 |
39 | $annotations = array();
40 |
41 | if (isset($bloques)) {
42 | // Revisar si es un valor constante o una asignacion
43 | foreach($bloques as $bloque) {
44 |
45 | $bloque = trim($bloque);
46 |
47 | if (strpos($bloque, '=') === false) {
48 | // no es una asignacion
49 | $annotation = new Annotation();
50 | if (trim($bloque) != "") {
51 | $annotation->Name = trim($bloque);
52 | $annotation->Value = null;
53 | $annotations[$annotation->Name] = $annotation;
54 | }
55 | }
56 | else {
57 | // es una asignacion
58 | $asignacion = explode('=', $bloque, 2);
59 |
60 | if (isset($asignacion[0])) {
61 | if (trim($asignacion[0]) != "") {
62 | $annotation = new Annotation();
63 | $annotation->Name = trim($asignacion[0]);
64 | $annotation->Value = trim($asignacion[1]);
65 | $annotations[$annotation->Name] = $annotation;
66 | }
67 | }
68 | }
69 | }
70 | }
71 |
72 | return $annotations;
73 | }
74 | }
--------------------------------------------------------------------------------
Total de líneas: 74
================================================================================
================================================================================
ARCHIVO #115: src/Dao/Entity/EntityDefinition.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Dao/Entity/EntityDefinition.php
Tamaño: 9.28 KB
--------------------------------------------------------------------------------
1 | Add($entityDefinition);
50 |
51 | // Actualizar REDIS
52 | // $redis = RedisSvc::Init();
53 |
54 | // // Si tenemos redis, actualizamos el valor de la coleccion
55 | // if (isset($redis)) {
56 | // $redis->set("gps-cache-entity-collection", serialize(self::$EntityColletion));
57 | // $redis->close();
58 | // }
59 | }
60 |
61 | private static function GetEntityCollection() {
62 |
63 | // if (!isset(self::$EntityColletion)) {
64 |
65 | // // Buscar las definiciones en Redis
66 | // $redis = RedisSvc::Init();
67 |
68 | // // Si tenemos redis, ver si podemos obtener la configuracion desde ahí
69 | // if (isset($redis)) {
70 | // $definition = $redis->get("gps-cache-entity-collection");
71 |
72 | // if (isset($definition) && $definition) {
73 | // $info = unserialize($definition);
74 | // $redis->close();
75 | // }
76 |
77 | // if (isset($info) && ($info)) {
78 | // self::$EntityColletion = $info;
79 | // }
80 | // }
81 |
82 | // Si no fue posible obtener la coleccion, deberemos crear una nueva
83 | if (!isset(self::$EntityColletion)) {
84 | // Creamos una coleccion nueva
85 | self::$EntityColletion = new GenericCollection(
86 | Key: "Entity", // << la propiedad "Entity" de la clase "EntityDefinition" que contiene el nombre de la entidad
87 | DtoName: EntityDefinition::class,
88 | Values: null,
89 | ReflectDto: false // No se debe realizar REFLECTION del DTO, se produciría un bucle infinito
90 | );
91 | }
92 | // }
93 |
94 | return self::$EntityColletion;
95 | }
96 |
97 | public static function Instance($entityName) {
98 |
99 | // Buscamos la entidad en la colección
100 | $col = self::GetEntityCollection();
101 |
102 | $entidad = $col->FirstWhere("Entity == '$entityName'");
103 |
104 | if (!isset($entidad) && $entidad == null) {
105 | // Si no encontramos la entidad, deberemos obtenerla mediante Reflection
106 | //$entidad = EntityDefinition::GetInstance(new \ReflectionClass($entityName));
107 | $entidad = EntityDefinition::GetInstance($entityName);
108 |
109 | // Debemos agregar la entidad a la coleccion (y actualizar redis)
110 | //self::AddEntityDefinitionToCollection($entidad);
111 | }
112 |
113 | return $entidad;
114 | }
115 |
116 | //public static function GetInstance(\ReflectionClass $entity) {
117 | public static function GetInstance(String $entity) {
118 |
119 | //$reflected = new \ReflectionClass($entity);
120 |
121 | // Instanciar el resultado
122 | $result = new EntityDefinition();
123 |
124 | $annotations = AnnotationHelper::FromClass($entity);
125 | $reflected = $annotations->Reflected;
126 |
127 | // Buscar atributo de entidad de la clase
128 | $entidad = $annotations->FindAttributeClass(Entity::class);
129 |
130 | $result->Entity = $reflected->getName();
131 |
132 | // Prefijo de tabla << TODO
133 | $result->TablePrefix = $reflected->getShortName();
134 |
135 | // Obtener la información respecto de la Entidad
136 | //$annotations = DocComment::GetClassAnnotations($entity);
137 | if (!isset($entidad->attribute->Schema) || $entidad->attribute->Schema == '') {
138 | //$result->Schema = 'dbo';
139 | $result->Schema = '';
140 | }
141 | else {
142 | $result->Schema = $entidad->attribute->Schema;
143 | }
144 |
145 | if (!isset($entidad->attribute->TableName) || $entidad->attribute->TableName == '') {
146 | $result->Table = (($result->Schema!='') ? $result->Schema . '.' : '') . $reflected->getShortName();
147 | }
148 | else {
149 | $result->Table = (($result->Schema!='') ? $result->Schema . '.' : '') . $entidad->attribute->TableName;
150 | }
151 |
152 | if (!isset($entidad->attribute->TablePrefix) || $entidad->attribute->TablePrefix == '') {
153 | $result->TablePrefix = $reflected->getShortName();
154 | }
155 | else {
156 | $result->TablePrefix = $entidad->attribute->TablePrefix;
157 | }
158 |
159 | if ($result->Table != $result->TablePrefix)
160 | $result->NamedTable = $result->Table . " " . $result->TablePrefix;
161 | else
162 | $result->NamedTable = $result->Table;
163 |
164 | $result->IsAuditable = (isset($entidad->attribute->Auditable) && $entidad->attribute->Auditable);
165 | $result->Display = $entidad->attribute->Display ?? '';
166 |
167 | // Obtener la información respecto de las propiedades
168 | $propiedades = get_class_vars($reflected->getName());
169 | $atributosPropiedades = $annotations->GetAttributeProperties(EntityField::class);
170 |
171 | foreach($propiedades as $propiedad=>$valor) {
172 |
173 | $property = PropertyDefinition::GetInstance($atributosPropiedades, $propiedad, new \ReflectionProperty($reflected->getName(), $propiedad));
174 |
175 | if ($property->IsKey && !isset($result->KeyProperty)) {
176 | $result->KeyProperty = $property;
177 | $result->AutoIncrement = $property->IsAutoIncrement;
178 |
179 | // Asignar el nombre de la propiedad "primary key" que tiene en la base de datos
180 | if (isset($property->ColumnName)) {
181 | $result->Key = $property->ColumnName;
182 | }
183 | else{
184 | $result->Key = $property->Name;
185 | }
186 |
187 | $result->KeyName = $property->Name;
188 | }
189 |
190 |
191 |
192 | // Si no se especifica el nombre de columna de la BD, sobreescribimos con
193 | // el nombre de la propiedad en la clase (se asume entonces que son iguales)
194 | if (!isset($property->ColumnName) || $property->ColumnName == "") {
195 | $property->ColumnName = $property->Name;
196 | }
197 |
198 | // Agregar a la lista de columnas
199 | if ($result->Fields != "")
200 | $result->Fields .= ", ";
201 |
202 | $result->Fields .= $property->ColumnName . ' AS ' . $property->Name;
203 |
204 | // Agregar a la lista de columnas no ignoradas (para usar en inserts y updates)
205 | if (!$property->Ignore) {
206 |
207 | // NOT IGNORED
208 | if ($result->NotIgnoredFields != "")
209 | $result->NotIgnoredFields .= ", ";
210 |
211 | $result->NotIgnoredFields .= $property->ColumnName;
212 |
213 | // NAMED NOT IGNORED
214 | if ($result->NamedNotIgnoredFields != "")
215 | $result->NamedNotIgnoredFields .= ", ";
216 |
217 | $result->NamedNotIgnoredFields .= $result->TablePrefix . "." . $property->ColumnName . ' AS "' . $property->Name . '"';
218 |
219 | // NAMED RENAMED NOT IGNORED
220 | if ($result->NamedRenamedNotIgnoredFields != "")
221 | $result->NamedRenamedNotIgnoredFields .= ", ";
222 |
223 | $result->NamedRenamedNotIgnoredFields .= $result->TablePrefix . "." . $property->ColumnName . ' AS "' . $result->TablePrefix . "." . $property->Name . '"';
224 |
225 | // NAMED
226 | // Agregar a la lista de columnas con nombre (solo las no ignoradas)
227 | if ($result->NamedFields != "")
228 | $result->NamedFields .= ", ";
229 |
230 | $result->NamedFields .= $result->TablePrefix . "." . $property->ColumnName . ' AS ' . $property->Name;
231 |
232 | // NAMED LISTED
233 | // Agregar a la lista de columnas sin nombre (solo las no ignoradas)
234 | if ($result->NamedListedFields != "")
235 | $result->NamedListedFields .= ", ";
236 |
237 | $result->NamedListedFields .= $result->TablePrefix . "." . $property->ColumnName;
238 | }
239 |
240 | // Agregar a la lista de campos de clase
241 | if ($result->ClassFields != "")
242 | $result->ClassFields .= ", ";
243 |
244 | $result->ClassFields .= $property->Name;
245 |
246 | // Agregar la propiedad a la colección
247 | $result->Properties[$property->Name] = $property;
248 | }
249 |
250 | return $result;
251 | }
252 |
253 | function __construct() {
254 | }
255 | }
--------------------------------------------------------------------------------
Total de líneas: 255
================================================================================
================================================================================
ARCHIVO #116: src/Dao/Entity/IAuditable.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Dao/Entity/IAuditable.php
Tamaño: 389 bytes
--------------------------------------------------------------------------------
1 | Name = $propiedad;
40 |
41 | if (isset($atributosPropiedades)) {
42 | $definicion = $atributosPropiedades->FirstWhere("propertyName == '" . $propiedad . "'");
43 |
44 | if (isset($definicion)) {
45 | $result->IsKey = $definicion->attribute->PrimaryKey;
46 | $result->IsAutoIncrement = $definicion->attribute->AutoIncrement;
47 | $result->ColumnName = ($definicion->attribute->ColumnName != '') ? $definicion->attribute->ColumnName : $propiedad;
48 | $result->ColumnType = $definicion->attribute->DataType;
49 | $result->IsNullable = $definicion->attribute->Nullable;
50 | $result->DefaultWhenNull = $definicion->attribute->DefaultWhenNull;
51 | $result->ForceDateValidation = $definicion->attribute->ForceDateValidation;
52 | $result->Ignore = $definicion->attribute->Ignore;
53 | $result->IsHtml = ($definicion->attribute->ColumnName == 'Html');
54 | $result->IsAuditable = (isset($definicion->attribute->Auditable) && $definicion->attribute->Auditable);
55 | $result->Display = $definicion->attribute->Display;
56 | $result->DisplayFormat = $definicion->attribute->DisplayFormat;
57 | }
58 | }
59 |
60 | /*
61 | // Obtener la información respecto de la Propiedad
62 | $annotations = DocComment::GetPropertyAnnotations($property);
63 |
64 | foreach($annotations as $annotation) {
65 |
66 | switch(strtolower($annotation->Name)) {
67 | case "key" : $result->IsKey = true; break;
68 | case "autoincrement" : $result->IsAutoIncrement = true;
69 | case "column" : if (isset($annotation->Value)) $result->ColumnName = $annotation->Value; break;
70 | case "columntype" : if (isset($annotation->Value)) $result->ColumnType = $annotation->Value; break;
71 | case "isnullable" : $result->IsNullable = true;
72 | case "defaultwhennull" : if (isset($annotation->Value)) $result->DefaultWhenNull = $annotation->Value; break;
73 | case "ignore" : $result->Ignore = true;
74 | }
75 |
76 | }
77 | */
78 |
79 | if (!isset($result->ColumnName) || $result->ColumnName == "") {
80 | $result->ColumnName = $result->Name;
81 | }
82 |
83 | return $result;
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
Total de líneas: 86
================================================================================
================================================================================
ARCHIVO #118: src/Dao/ExecuteDao.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Dao/ExecuteDao.php
Tamaño: 6.53 KB
--------------------------------------------------------------------------------
1 | beginTransaction()) {
33 | self::$isTransactionOpened = true;
34 | return $conn;
35 | }
36 | }
37 | else {
38 | return null;
39 | }
40 | }
41 |
42 | public static function CommitTransaction($transaction) {
43 | if ($transaction->commit()) {
44 | $transaction = null;
45 | self::$isTransactionOpened = false;
46 | }
47 | }
48 |
49 | public static function RollbackTransaction($transaction) {
50 | if ($transaction->rollback()) {
51 | $transaction = null;
52 | self::$isTransactionOpened = false;
53 | }
54 | }
55 |
56 | public function ExecuteStatement($stmt, $fetchStyle = \PDO::FETCH_ASSOC)
57 | {
58 | $retorno = $stmt->execute();
59 | if (!$retorno)
60 | return null;
61 | else
62 | return $stmt->fetchAll($fetchStyle);
63 | }
64 |
65 | public function Execute($stmt)
66 | {
67 | $stmt->execute();
68 | }
69 |
70 | public function ExecuteStatementForObject($stmt)
71 | {
72 | $stmt->setFetchMode(PDO::FETCH_CLASS, $this->EntityDefinition->Entity);
73 | $stmt->execute();
74 | $retorno = $stmt->fetchObject($this->EntityDefinition->Entity);
75 | if (!$retorno)
76 | return null;
77 | else
78 | return $retorno;
79 | }
80 |
81 | public function ExecuteStatementForObjectByKeys($stmt,$keys)
82 | {
83 | $stmt->setFetchMode(PDO::FETCH_CLASS, $this->EntityDefinition->Entity);
84 | $stmt->execute($keys);
85 | $retorno = $stmt->fetchObject($this->EntityDefinition->Entity);
86 | if (!$retorno)
87 | return null;
88 | else
89 | return $retorno;
90 | }
91 |
92 | public function ExecuteStatementForObjects($stmt)
93 | {
94 | $stmt->setFetchMode(PDO::FETCH_CLASS, $this->EntityDefinition->Entity);
95 | $stmt->execute();
96 | $retorno = $stmt->fetchAll(PDO::FETCH_CLASS, $this->EntityDefinition->Entity);
97 |
98 | if (!$retorno)
99 | return null;
100 | else
101 | return $retorno;
102 | }
103 |
104 | public function ExecuteStatementForQueryable($stmt)
105 | {
106 |
107 | $stmt->setFetchMode(PDO::FETCH_OBJ);
108 | $stmt->execute();
109 | $retorno = $stmt->fetchAll();
110 |
111 | if (!$retorno)
112 | return null;
113 | else
114 | return $retorno;
115 | }
116 |
117 | public function ExecuteScalar($stmt) {
118 | $stmt->execute();
119 | return $stmt->fetchColumn();
120 | }
121 |
122 | public function ExecuteStatementForObjectsToFile($stmt, $filename = null)
123 | {
124 | $stmt->setFetchMode(PDO::FETCH_CLASS, $this->EntityDefinition->Entity);
125 | $stmt->execute();
126 |
127 | $pathFile = $this->CreateFileSet($stmt, $filename);
128 |
129 | return $pathFile;
130 | }
131 |
132 | public function ExecuteStatementToFile($stmt, $filename = null, $localDataFolder = '')
133 | {
134 | if (isset($localDataFolder) && $localDataFolder != '') {
135 | $this->dir = $localDataFolder;
136 | }
137 |
138 | $stmt->setFetchMode(PDO::FETCH_OBJ);
139 | $stmt->execute();
140 |
141 | $pathFile = $this->CreateFileSet($stmt, $filename,PDO::FETCH_OBJ);
142 | return $pathFile;
143 | }
144 |
145 |
146 |
147 | private function CreateFileJson($stmt, $filename, $pdoType = PDO::FETCH_CLASS)
148 | {
149 | if (!is_dir($this->dir))
150 | mkdir($this->dir, 0755, true);
151 |
152 | if (!isset($filename))
153 | $filename = $this->dir . _guid() . ".json";
154 | else
155 | $filename = $this->dir . $filename;
156 |
157 | $file = fopen($filename, 'w');
158 |
159 | fwrite($file, "\xEF\xBB\xBF");
160 |
161 | fwrite($file, "[");
162 | $primerElemento = true;
163 |
164 | while ($row = $stmt->fetch(PDO::FETCH_CLASS)) {
165 | $json = json_encode($row, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
166 | if ($primerElemento)
167 | $primerElemento = false;
168 | else
169 | $json = "," . $json;
170 |
171 | fwrite($file, $json);
172 | }
173 | fwrite($file, "]");
174 | fclose($file);
175 | return $filename;
176 | }
177 |
178 | private function CreateFileSet($stmt, $filename, $pdoType = PDO::FETCH_CLASS)
179 | {
180 | if (!is_dir($this->dir))
181 | mkdir($this->dir, 0755, true);
182 |
183 | if (!isset($filename))
184 | $filename = $this->dir . _guid() . ".set";
185 | else
186 | $filename = $this->dir . $filename;
187 |
188 | $file = fopen($filename, 'w');
189 |
190 | //fwrite($file, "\xEF\xBB\xBF");
191 |
192 | while ($row = $stmt->fetch($pdoType)) {
193 | $json = json_encode($row, JSON_UNESCAPED_UNICODE);
194 | fwrite($file, $json."\n");
195 | }
196 |
197 | fclose($file);
198 | return $filename;
199 | }
200 |
201 | private function CreateFileCsv($stmt, $filename)
202 | {
203 | if (!is_dir($this->dir))
204 | mkdir($this->dir, 0755, true);
205 |
206 | if (!isset($filename))
207 | $filename = $this->dir . _guid() . ".csv";
208 | else
209 | $filename = $this->dir . $filename;
210 |
211 | $file = fopen($filename, 'w');
212 |
213 | fwrite($file, "\xEF\xBB\xBF");
214 |
215 | $setHeardes = true;
216 |
217 | while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
218 | if ($setHeardes) {
219 | $keys = array_keys($row);
220 | fputcsv($file, $keys);
221 | $setHeardes = false;
222 | }
223 |
224 | fputcsv($file, $row);
225 | }
226 |
227 | fclose($file);
228 | return $filename;
229 | }
230 | }
231 | }
232 |
--------------------------------------------------------------------------------
Total de líneas: 232
================================================================================
================================================================================
ARCHIVO #119: src/Dao/Format.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Dao/Format.php
Tamaño: 480 bytes
--------------------------------------------------------------------------------
1 | ColumnType) == 'datetime') {
28 | if ($this->Domain->Type == 'oracle' && strtolower($property->ColumnType) == 'datetime') {
29 | return "TO_DATE(:" . $property->ColumnName . ", 'yyyy-mm-dd hh24:mi:ss')";
30 | }
31 | else if ($this->Domain->Type == 'sqlserver' && strtolower($property->ColumnType) == 'datetime') {
32 | return "convert(datetime, :" . $property->ColumnName . ", 20)";
33 | }
34 | }
35 |
36 | // cualquier otro caso
37 | return ':' . $property->ColumnName;
38 | }
39 |
40 | private function Value($property, $entity) {
41 |
42 | $value = $this->ReflectedEntity
43 | ->getProperty($property->Name)
44 | ->getValue($entity);
45 |
46 | if (strtolower($property->ColumnType) == 'datetime') {
47 |
48 | if ($property->ForceDateValidation) {
49 | return _CdateautoDb($value);
50 | }
51 | else {
52 | if (isset($value))
53 | return new \DateTime($value);
54 | else
55 | return null;
56 | }
57 | }
58 |
59 | // cualquier otro caso
60 | return $value;
61 |
62 | }
63 |
64 | public function Update($entity, $transaction = null, ?IAuditable $auditable = null) {
65 |
66 | // Revisar auditoria
67 | // -----------------------------------------
68 | if (isset($auditable)) {
69 | try {
70 | $key = $this->EntityDefinition->KeyProperty->Name;
71 | $current = $this->Find($entity->$key);
72 |
73 | $audit = new AuditInfo(Auditable: $auditable, Definition : $this->EntityDefinition, CurrentEntity: $current, NewEntity: $entity);
74 | $audit->Run();
75 | }
76 | catch (\Exception $ex) {}
77 | }
78 | // -----------------------------------------
79 |
80 |
81 | if ($this->ReflectedEntity == null)
82 | $this->ReflectedEntity = new \ReflectionClass($this->EntityDefinition->Entity);
83 |
84 | $fields = array();
85 | $bindings = array();
86 | $values = array();
87 | $bindingCasts = array(); // para casos especiales en los cuales se debe interponer algun cast o formateador al campo
88 | $types = array();
89 |
90 | // Construir la sentencia SQL de actualización
91 | $qry = 'UPDATE '. $this->EntityDefinition->Table.' SET ';
92 |
93 | $idx = 0;
94 | foreach($this->EntityDefinition->Properties as $property) {
95 |
96 | if (!$property->Ignore && !$property->IsKey) {
97 |
98 | $fields[$idx] = $property->ColumnName;
99 | $bindings[$idx] = ':' . $property->ColumnName;
100 |
101 | if ($property->ColumnType == 'int')
102 | $types[$idx] = 'int';
103 | else
104 | $types[$idx] = '';
105 |
106 | $bindingCasts[$idx] = $this->Cast($property);
107 | // if ($this->Domain->Type == 'oracle' && strtolower($property->ColumnType) == 'datetime') {
108 | // $bindingCasts[$idx] = "TO_DATE(:" . $property->ColumnName . ", 'yyyy-mm-dd hh24:mi:ss')";
109 | // }
110 | // else if ($this->Domain->Type == 'sqlserver' && strtolower($property->ColumnType) == 'datetime') {
111 | // $bindingCasts[$idx] = "convert(datetime, :" . $property->ColumnName . ", 20)";
112 | // }
113 | // else {
114 | // $bindingCasts[$idx] = ':' . $property->ColumnName;
115 | // }
116 |
117 | $values[$idx] = $this->Value($property, $entity);
118 | // $values[$idx] = $this->ReflectedEntity
119 | // ->getProperty($property->Name)
120 | // ->getValue($entity);
121 |
122 | // Agregar instrucción SET a la sentencia
123 | if ($idx > 0)
124 | $qry .= ', ';
125 |
126 | $qry .= $property->ColumnName . ' = ' . $bindingCasts[$idx];
127 |
128 | $idx++;
129 | }
130 | }
131 |
132 | // Agregar la condición de selección
133 | $qry .= ' WHERE ' . $this->EntityDefinition->Key . ' = :' . $this->EntityDefinition->Key;
134 |
135 | // Preparar la sentencia
136 | if (!isset($transaction)) {
137 | $transaction = $this->Connection;
138 | }
139 | $stmt = $transaction->prepare($qry);
140 |
141 | // Asignar el enlazamiento (bindings)
142 | for( $idxb = 0; $idxb < count($bindings); $idxb++) {
143 | $value = $values[$idxb];
144 | $bind = $bindings[$idxb];
145 |
146 | if(is_int($value) || $types[$idxb] == 'int') {
147 | $param = PDO::PARAM_INT;
148 | }
149 | elseif(is_double($value)) {
150 | $param = PDO::PARAM_STR;
151 | }
152 | elseif(is_float($value)) {
153 | $param = PDO::PARAM_STR;
154 | }
155 | elseif(is_bool($value)) {
156 | $param = PDO::PARAM_BOOL;
157 | }
158 | elseif(is_null($value)) {
159 | $param = PDO::PARAM_NULL;
160 | }
161 | elseif(is_string($value)) {
162 | $param = PDO::PARAM_STR;
163 | }
164 | elseif($value instanceof \DateTime) {
165 | $param = PDO::PARAM_STR;
166 | $value = $value->format('Y-m-d H:i:s');
167 | }
168 | else
169 | $param = FALSE;
170 |
171 | $stmt->bindValue("$bind", $value, $param);
172 | }
173 |
174 |
175 | // Asignar el enlazamiento de la KEY
176 | $keyParam = PDO::PARAM_INT;
177 | $keyBind = ':'.$this->EntityDefinition->Key;
178 |
179 | $keyValue = $this->ReflectedEntity
180 | ->getProperty($this->EntityDefinition->KeyProperty->Name)
181 | ->getValue($entity);
182 |
183 | $stmt->bindValue("$keyBind", $keyValue, $keyParam);
184 |
185 | // Ejecutar la sentencia
186 | $stmt->execute();
187 | }
188 |
189 | public function Insert($entity, $transaction = null, ?IAuditable $auditable = null) {
190 |
191 | // Revisar auditoria
192 | // -----------------------------------------
193 | if (isset($auditable)) {
194 | try {
195 | $audit = new AuditInfo(Auditable: $auditable, NewEntity: $entity, Definition: $this->EntityDefinition);
196 | $audit->Run();
197 | }
198 | catch (\Exception $ex) {}
199 | }
200 | // -----------------------------------------
201 |
202 | $oracleNewId = 0;
203 |
204 | if ($this->ReflectedEntity == null)
205 | $this->ReflectedEntity = new \ReflectionClass($this->EntityDefinition->Entity);
206 |
207 | $fields = array();
208 | $bindings = array();
209 | $values = array();
210 | $bindingCasts = array(); // para casos especiales en los cuales se debe interponer algun cast o formateador al campo
211 | $types = array();
212 |
213 | $idx = 0;
214 |
215 | // if ($this->Domain->Type == 'oracle') {
216 | // // Se debe obtener el siguiente elemento en la secuencia
217 | // $oracleNewId = $this->Connection->sequenceNextVal($this->EntityDefinition->Table . "_SEQ");
218 |
219 | // $fields[0] = $this->EntityDefinition->KeyProperty->ColumnName;
220 | // $bindings[0] = ':' . $this->EntityDefinition->KeyProperty->ColumnName;
221 | // $bindingCasts[0] = ':' . $this->EntityDefinition->KeyProperty->ColumnName;
222 | // $values[0] = $oracleNewId;
223 | // //$types[0] = 'sequence';
224 | // $types[0] = '';
225 | // $idx++;
226 | // }
227 |
228 | foreach($this->EntityDefinition->Properties as $property) {
229 |
230 | if (!$property->Ignore && !$property->IsKey) {
231 |
232 | $fields[$idx] = $property->ColumnName;
233 | $bindings[$idx] = ':' . $property->ColumnName;
234 |
235 | // if ($property->ColumnType == 'int')
236 | // $types[$idx] = 'int';
237 | // else if ($property->ColumnType == 'datetime')
238 | // $types[$idx] = 'datetime';
239 | // else
240 | $types[$idx] = '';
241 |
242 | $bindingCasts[$idx] = $this->Cast($property);
243 | // if ($this->Domain->Type == 'oracle' && strtolower($property->ColumnType) == 'datetime') {
244 | // $bindingCasts[$idx] = "TO_DATE(:" . $property->ColumnName . ", 'yyyy-mm-dd hh24:mi:ss')";
245 | // }
246 | // else if ($this->Domain->Type == 'sqlserver' && strtolower($property->ColumnType) == 'datetime') {
247 | // $bindingCasts[$idx] = "convert(datetime, :" . $property->ColumnName . ", 20)";
248 | // }
249 | // else {
250 | // $bindingCasts[$idx] = ':' . $property->ColumnName;
251 | // }
252 |
253 | $values[$idx] = $this->Value($property, $entity);
254 | // $values[$idx] = $this->ReflectedEntity
255 | // ->getProperty($property->Name)
256 | // ->getValue($entity);
257 |
258 | $idx++;
259 | }
260 | }
261 |
262 | // Construir la sentencia SQL de inserción
263 | $qry = 'INSERT INTO '. $this->EntityDefinition->Table . ' ('.join(",", $fields).') VALUES ('.join(",", $bindingCasts).')';
264 |
265 | // Preparar la sentencia
266 | if (!isset($transaction)) {
267 | $transaction = $this->Connection;
268 | }
269 | $stmt = $transaction->prepare($qry);
270 |
271 | // Asignar el enlazamiento (bindings)
272 | for( $idxb = 0; $idxb < count($bindings); $idxb++) {
273 | $value = $values[$idxb];
274 | $bind = $bindings[$idxb];
275 |
276 | if(is_int($value) || $types[$idxb] == 'sequence' || $types[$idxb] == 'int') {
277 | $param = PDO::PARAM_INT;
278 | }
279 | elseif(is_double($value)) {
280 | $param = PDO::PARAM_STR;
281 | }
282 | elseif(is_float($value)) {
283 | $param = PDO::PARAM_STR;
284 | }
285 | elseif(is_bool($value)) {
286 | $param = PDO::PARAM_BOOL;
287 | }
288 | elseif(is_null($value)) {
289 | $param = PDO::PARAM_NULL;
290 | }
291 | elseif(is_string($value)) {
292 | $param = PDO::PARAM_STR;
293 | }
294 | elseif($value instanceof \DateTime) {
295 | $param = PDO::PARAM_STR;
296 | $value = $value->format('Y-m-d H:i:s');
297 | }
298 | else
299 | $param = FALSE;
300 |
301 | $stmt->bindValue("$bind", $value, $param);
302 | }
303 |
304 | // Ejecutar la sentencia y obtener el ID del nuevo registro
305 | /*
306 | if (!self::IsTransactionOpen()) {
307 | $this->Connection->beginTransaction();
308 | }
309 | */
310 | $result = $stmt->execute();
311 |
312 | if ($this->Domain->Type == 'oracle') {
313 | $newID = $oracleNewId;
314 | }
315 | else if ($this->Domain->Type == 'mysql') {
316 | $newID = $transaction->lastInsertId();
317 | }
318 | else {
319 | $newID = $transaction->lastInsertId();
320 | }
321 |
322 | /*
323 | if (!self::IsTransactionOpen()) {
324 | $this->Connection->commit();
325 | }
326 | */
327 |
328 | if ($newID <= 0)
329 | return null;
330 |
331 | // Asignar el nuevo ID a la entidad
332 | $reflectionClass = new \ReflectionClass($this->EntityDefinition->Entity);
333 | $reflectionClass->getProperty($this->EntityDefinition->KeyName)->setValue($entity, intval($newID));
334 |
335 | // Retornar la entidad con el nuevo ID asignado a la llave
336 | return $entity;
337 | }
338 |
339 | public function Delete($keyValue, $transaction = null)
340 | {
341 | $qry = 'DELETE FROM '. $this->EntityDefinition->Table .' WHERE '. $this->EntityDefinition->Key. ' = :' . $this->EntityDefinition->Key;
342 |
343 | if (!isset($transaction)) {
344 | $transaction = $this->Connection;
345 | }
346 | $stmt = $transaction->prepare($qry);
347 |
348 | // Asignar la condicion de selección
349 | $keyParam = PDO::PARAM_INT;
350 | $keyBind = ':'.$this->EntityDefinition->Key;
351 |
352 | $stmt->bindValue("$keyBind", $keyValue, $keyParam);
353 |
354 | $stmt->execute();
355 | }
356 |
357 | public function LogicDelete($keyValue, $transaction = null) {
358 |
359 | $qry = 'UPDATE '. $this->EntityDefinition->Table .' SET IndEliminado = 1 WHERE '. $this->EntityDefinition->Key. ' = :' . $this->EntityDefinition->Key;
360 |
361 | if (!isset($transaction)) {
362 | $transaction = $this->Connection;
363 | }
364 | $stmt = $transaction->prepare($qry);
365 |
366 | // Asignar la condicion de selección
367 | $keyParam = PDO::PARAM_INT;
368 | $keyBind = ':'.$this->EntityDefinition->Key;
369 |
370 | $stmt->bindValue("$keyBind", $keyValue, $keyParam);
371 |
372 | $stmt->execute();
373 | }
374 |
375 | public function DeleteBy($bindings, $transaction = null)
376 | {
377 | $qry = 'DELETE FROM ' . $this->EntityDefinition->Table;
378 |
379 | /* @var $var BindVariable */
380 | $count = 0;
381 | $where = '';
382 | $bind = array();
383 | foreach ($bindings as $key => $var) {
384 |
385 | if ($count > 0) {
386 | $where .= '
387 | AND
388 | ';
389 | }
390 |
391 | if ($var->Operator == 'BETWEEN') {
392 | $where .= $var->Field . ' BETWEEN :var' . $count . ' AND :var' . ($count + 1) . ' ';
393 |
394 | $bind['var' . $count] = $var->Operand1;
395 | $count++;
396 | $bind['var' . $count] = $var->Operand2;
397 | } else {
398 | $where .= $var->Field . ' ' . $var->Operator . ' :var' . $count . ' ';
399 | $bind['var' . $count] = $var->Operand1;
400 | }
401 |
402 | $count++;
403 | }
404 |
405 | if ($where != '') {
406 | $qry .= ' WHERE ' . $where;
407 | } else {
408 | throw new \Exception("NO PUDE REALIZAR UNA ELIMINACION DESDE UNA TABLA SIN CONDICIONES DE EXCLUSION -WHERE-");
409 | return;
410 | }
411 |
412 | // preparar sentencia
413 | if (!isset($transaction)) {
414 | $transaction = $this->Connection;
415 | }
416 | $stmt = $transaction->prepare($qry);
417 |
418 | // ligar variables
419 | foreach ($bind as $v => $value) {
420 | if(is_int($value))
421 | $param = PDO::PARAM_INT;
422 | elseif(is_bool($value))
423 | $param = PDO::PARAM_BOOL;
424 | elseif(is_null($value))
425 | $param = PDO::PARAM_NULL;
426 | elseif(is_string($value))
427 | $param = PDO::PARAM_STR;
428 | else
429 | $param = FALSE;
430 |
431 | if($param)
432 | $stmt->bindValue(":$v", $value, $param);
433 | }
434 |
435 | $stmt->execute();
436 | }
437 |
438 | public function LogicDeleteBy($bindings, $transaction = null)
439 | {
440 | $qry = 'UPDATE ' . $this->EntityDefinition->Table . " SET IndEliminado = 1 ";
441 |
442 | /* @var $var BindVariable */
443 | $count = 0;
444 | $where = '';
445 | $bind = array();
446 | foreach ($bindings as $key => $var) {
447 |
448 | if ($count > 0) {
449 | $where .= '
450 | AND
451 | ';
452 | }
453 |
454 | if ($var->Operator == 'BETWEEN') {
455 | $where .= $var->Field . ' BETWEEN :var' . $count . ' AND :var' . ($count + 1) . ' ';
456 |
457 | $bind['var' . $count] = $var->Operand1;
458 | $count++;
459 | $bind['var' . $count] = $var->Operand2;
460 | } else {
461 | $where .= $var->Field . ' ' . $var->Operator . ' :var' . $count . ' ';
462 | $bind['var' . $count] = $var->Operand1;
463 | }
464 |
465 | $count++;
466 | }
467 |
468 | if ($where != '') {
469 | $qry .= ' WHERE ' . $where;
470 | } else {
471 | throw new \Exception("NO PUDE REALIZAR UNA ELIMINACION DESDE UNA TABLA SIN CONDICIONES DE EXCLUSION -WHERE-");
472 | return;
473 | }
474 |
475 | // preparar sentencia
476 | if (!isset($transaction)) {
477 | $transaction = $this->Connection;
478 | }
479 | $stmt = $transaction->prepare($qry);
480 |
481 | // ligar variables
482 | foreach ($bind as $v => $value) {
483 | if(is_int($value))
484 | $param = PDO::PARAM_INT;
485 | elseif(is_bool($value))
486 | $param = PDO::PARAM_BOOL;
487 | elseif(is_null($value))
488 | $param = PDO::PARAM_NULL;
489 | elseif(is_string($value))
490 | $param = PDO::PARAM_STR;
491 | else
492 | $param = FALSE;
493 |
494 | if($param)
495 | $stmt->bindValue(":$v", $value, $param);
496 | }
497 |
498 | $stmt->execute();
499 | }
500 | }
501 | }
502 |
--------------------------------------------------------------------------------
Total de líneas: 502
================================================================================
================================================================================
ARCHIVO #122: src/Dao/OperatorEnum.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Dao/OperatorEnum.php
Tamaño: 551 bytes
--------------------------------------------------------------------------------
1 | ';
17 | public const GR = '>';
18 | public const GREQ = '>=';
19 | public const LO = '<';
20 | public const LOEQ = '<=';
21 | public const BET = 'BETWEEN';
22 | public const IN = 'IN';
23 |
24 | }
--------------------------------------------------------------------------------
Total de líneas: 24
================================================================================
================================================================================
ARCHIVO #123: src/Dao/Queryable.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Dao/Queryable.php
Tamaño: 23.83 KB
--------------------------------------------------------------------------------
1 |
25 | */
26 | class Queryable {
27 |
28 | private static $ConnectionType = null;
29 | private $idxElement = 0;
30 |
31 | public static function Init(string $ConnectionType) {
32 | self::$ConnectionType = $ConnectionType;
33 | }
34 |
35 | private $Definitions = [];
36 | private $FromDefinition = null;
37 | private $JoinDefinitions = null;
38 | private $LeftJoinDefinitions = null;
39 | private $WithDefinitions = null;
40 | private $WhereDefinitions = null;
41 | private $Order = '';
42 | private int $Top = 0;
43 | private bool $UseDistinct = false;
44 | private $Key = null;
45 |
46 | public function __construct(
47 | )
48 | {
49 | if (!isset(self::$ConnectionType)) {
50 | throw new \Exception('Debe inicializar la conexión por defecto antes de instanciar esta clase. Ej: Queryable::Init(ConnectionTypeEnum::MYSQL)');
51 | }
52 |
53 | $this->JoinDefinitions = new GenericCollection();
54 | $this->LeftJoinDefinitions = new GenericCollection();
55 | $this->WithDefinitions = new GenericCollection();
56 | $this->WhereDefinitions = new GenericCollection();
57 | }
58 |
59 | private function AddDefinition($definition, $definitionType) {
60 |
61 | $definition->Type = $definitionType;
62 |
63 | $this->Definitions[$this->idxElement] = $definition;
64 | $this->idxElement++;
65 |
66 | }
67 |
68 | /**
69 | * @param string $entity
70 | *
71 | * Agrega la entidad principal de la consulta
72 | *
73 | * @return Queryable
74 | */
75 | public function From(string $entity) {
76 |
77 | $this->FromDefinition = EntityDefinition::Instance($entity);
78 |
79 | return $this;
80 | }
81 |
82 | /**
83 | * @param string $entityClass
84 | *
85 | * Agrega una inclusión Join de todas las entidades hijas con la entidad padre principal.
86 | * La entidad padre debe contener una propiedad que tenga el nombre de la entidad hija en plural.
87 | * Si no existe el nombre, se creará una propiedad nueva.
88 | *
89 | * Ej:
90 | *
91 | * class Mantencion {
92 | * // Key AutoIncrement
93 | * public $IdMantencion = 0;
94 | * public $Descripcion = '';
95 | * public $IdTipoEstado = '';
96 | * public $Actividades = array(); << aca se agregará la coleccion JOIN
97 | * }
98 | *
99 | * class Actividad {
100 | * // Key, AutoIncrement
101 | * public $IdActividad = 0;
102 | * public $Description = '';
103 | * // Foreign=Mantencion
104 | * public $IdMantencion = 0;
105 | * }
106 | *
107 | * $qry = (new Queryable())
108 | * ->From(Mantencion::class)
109 | * ->Join(Actividad::class);
110 | *
111 | * @return Queryable
112 | */
113 | public function Join(string $entity, $foreignKey = '', $parentKey = '') {
114 |
115 | $entityDefinition = EntityDefinition::Instance($entity);
116 |
117 | if ($foreignKey != '')
118 | $entityDefinition->CustomForeignKey = $foreignKey;
119 |
120 | if ($parentKey != '')
121 | $entityDefinition->CustomParentKey = $parentKey;
122 |
123 | $this->JoinDefinitions->Add($entityDefinition);
124 | $this->AddDefinition($entityDefinition, DefinitionTypeEnum::JOIN);
125 |
126 | return $this;
127 | }
128 |
129 |
130 |
131 | /**
132 | * @param string $entityClass
133 | *
134 | * Agrega una inclusión LEFT Join de todas las entidades hijas con la entidad padre principal.
135 | * La entidad padre debe contener una propiedad que tenga el nombre de la entidad hija en plural.
136 | * Si no existe el nombre, se creará una propiedad nueva.
137 | *
138 | * Ej:
139 | *
140 | * class Mantencion {
141 | * // Key AutoIncrement
142 | * public $IdMantencion = 0;
143 | * public $Descripcion = '';
144 | * public $IdTipoEstado = '';
145 | * public $Actividades = array(); << aca se agregará la coleccion LEFT JOIN
146 | * }
147 | *
148 | * class Actividad {
149 | * // Key, AutoIncrement
150 | * public $IdActividad = 0;
151 | * public $Description = '';
152 | * // Foreign=Mantencion
153 | * public $IdMantencion = 0;
154 | * }
155 | *
156 | * $qry = (new Queryable())
157 | * ->From(Mantencion::class)
158 | * ->LeftJoin(Actividad::class);
159 | *
160 | * @return Queryable
161 | */
162 | public function LeftJoin(string $entity, $foreignKey = '', $parentKey = '') {
163 |
164 | $entityDefinition = EntityDefinition::Instance($entity);
165 |
166 | if ($foreignKey != '')
167 | $entityDefinition->CustomForeignKey = $foreignKey;
168 |
169 | if ($parentKey != '')
170 | $entityDefinition->CustomParentKey = $parentKey;
171 |
172 | $this->LeftJoinDefinitions->Add($entityDefinition);
173 | $this->AddDefinition($entityDefinition, DefinitionTypeEnum::LEFTJOIN);
174 |
175 | return $this;
176 | }
177 |
178 | /**
179 | * @param string $entity
180 | *
181 | * Agrega una inclusión de la entidad parent dentro de la entidad hija principal como un único elemento.
182 | * La entidad principal (hija) debe contener una propiedad que tenga el mismo nombre de la entidad referenciada (padre).
183 | * Si no existe el nombre, se creará una propiedad nueva.
184 | *
185 | * Ej:
186 | *
187 | * class Mantencion { << esta es la entidad hija
188 | * // Key AutoIncrement
189 | * public $IdMantencion = 0;
190 | * public $Descripcion = '';
191 | * // ForeignKey=TipoEstado
192 | * public $IdTipoEstado = '';
193 | * public $TipoEstado = null; << aca se agregará el elemento enlazado
194 | * }
195 | *
196 | * class TipoEstado { << esta es la entidad padre
197 | * // Key, AutoIncrement
198 | * public $IdTipoEstado = 0;
199 | * public $Description = '';
200 | * }
201 | *
202 | * $qry = (new Queryable())
203 | * ->From('Mantencion')
204 | * ->With('TipoEstado');
205 | *
206 | * @return Queryable
207 | */
208 | public function With(string $entity, $foreignKey = '', $parentKey = '') {
209 |
210 | $entityDefinition = EntityDefinition::Instance($entity);
211 |
212 | if ($foreignKey != '')
213 | $entityDefinition->CustomForeignKey = $foreignKey;
214 |
215 | if ($parentKey != '')
216 | $entityDefinition->CustomParentKey = $parentKey;
217 |
218 | $entityDefinition->LeftWith = false;
219 |
220 | $this->WithDefinitions->Add($entityDefinition);
221 | $this->AddDefinition($entityDefinition, DefinitionTypeEnum::WITH);
222 |
223 | return $this;
224 | }
225 |
226 | public function LeftWith(string $entity, $foreignKey = '', $parentKey = '') {
227 |
228 | $entityDefinition = EntityDefinition::Instance($entity);
229 |
230 | if ($foreignKey != '')
231 | $entityDefinition->CustomForeignKey = $foreignKey;
232 |
233 | if ($parentKey != '')
234 | $entityDefinition->CustomParentKey = $parentKey;
235 |
236 | $entityDefinition->LeftWith = true;
237 |
238 | $this->WithDefinitions->Add($entityDefinition);
239 | $this->AddDefinition($entityDefinition, DefinitionTypeEnum::LEFTWITH);
240 |
241 | return $this;
242 | }
243 |
244 | /**
245 | * @param string $condition
246 | * @param ... $params
247 | *
248 | * Agrega una condición de filtro a la entidad principal de la consulta.
249 | * Se pueden definir variables enlazadas con el símbolo "?". Para cada variable enlazada debe existir un parametro en la llamada a la funcion.
250 | * Las llamadas a WHERE se pueden encadenar (la serie de WHERE encadenados se incorporarán con AND)
251 | *
252 | * Ej:
253 | *
254 | * class Mantencion {
255 | * // Key AutoIncrement
256 | * public $IdMantencion = 0;
257 | * public $Descripcion = '';
258 | * // ForeignKey=TipoEstado
259 | * public $IdTipoEstado = '';
260 | * }
261 | *
262 | * $qry = (new Queryable())
263 | * ->From('Mantencion')
264 | * ->Where('IdTipoEstado = ? AND FechaInicioProgramada BETWEEN ? AND ?', 1, $dtInicio, new \DateTime())
265 | *
266 | * @return Queryable
267 | */
268 | public function Where($condition, ...$params) {
269 |
270 | $where = array();
271 |
272 | $where['Condition'] = $condition;
273 | $whereParams = array();
274 |
275 | if (isset($params)) {
276 | $paramQ = count($params);
277 | $placeQ = substr_count($condition, "?");
278 |
279 | if ($paramQ != $placeQ) {
280 | throw new \Exception("La cantidad de parametros ($paramQ) no concuerda con la cantidad de variables ($placeQ)");
281 | }
282 |
283 |
284 | foreach($params as $p) {
285 | array_push($whereParams, $p);
286 | }
287 | }
288 |
289 | $where['Parameters'] = $whereParams;
290 |
291 | $this->WhereDefinitions->Add((object)$where);
292 |
293 | return $this;
294 | }
295 |
296 | public function OrderBy($condition) {
297 | $this->Order = $condition;
298 | return $this;
299 | }
300 |
301 | public function Key($key) {
302 | $this-> FromDefinition -> Key = $key;
303 | return $this;
304 | }
305 |
306 | public function Top(int $recordNumber) {
307 | $this->Top = $recordNumber;
308 | return $this;
309 | }
310 |
311 | public function Distinct() {
312 | $this->UseDistinct = true;
313 | return $this;
314 | }
315 |
316 | /**
317 | *
318 | * Construye la sentencia de consulta en base a los parámetros especificados
319 | *
320 | *
321 | * @return object
322 | */
323 | public function Build() {
324 |
325 | if (!isset($this->FromDefinition)) {
326 | throw new \Exception("No se ha definido la entidad principal");
327 | }
328 |
329 | // $joins = $this->GetJoins($this->JoinDefinitions, $this->FromDefinition, false);
330 | // $leftjoins = $this->GetJoins($this->LeftJoinDefinitions, $this->FromDefinition, true);
331 | // $withs = $this->GetWiths($this->WithDefinitions, $this->FromDefinition);
332 |
333 | //$joins->AddRange($withs);
334 |
335 | $qryJoin = "";
336 | $fieldsJoin = "";
337 |
338 | // Leer en orden
339 | foreach($this->Definitions as $definition) {
340 |
341 | switch ($definition->Type) {
342 |
343 | case DefinitionTypeEnum::JOIN:
344 |
345 | $join = $this->GetJoin($definition, $this->FromDefinition);
346 |
347 | break;
348 |
349 | case DefinitionTypeEnum::LEFTJOIN:
350 |
351 | $join = $this->GetJoin($definition, $this->FromDefinition, true);
352 |
353 | break;
354 |
355 | case DefinitionTypeEnum::WITH:
356 |
357 | $join = $this->GetWith($definition, $this->FromDefinition);
358 |
359 | break;
360 |
361 | case DefinitionTypeEnum::LEFTWITH:
362 |
363 | $join = $this->GetWith($definition, $this->FromDefinition);
364 |
365 | break;
366 | }
367 |
368 | if ($qryJoin != "") $qryJoin .= "\n";
369 | $qryJoin .= $join->JoinSentence;
370 |
371 | if ($fieldsJoin != "")
372 | $fieldsJoin .= ",\n\t";
373 | $fieldsJoin .= $join->JoinFields;
374 | }
375 |
376 | // if ($joins->Count() > 0) {
377 | // foreach($joins as $join) {
378 | // if ($qryJoin != "") $qryJoin .= "\n";
379 | // $qryJoin .= $join->JoinSentence;
380 |
381 | // if ($fieldsJoin != "")
382 | // $fieldsJoin .= ",\n\t";
383 | // $fieldsJoin .= $join->JoinFields;
384 | // }
385 | // }
386 |
387 | // if ($leftjoins->Count() > 0) {
388 | // foreach($leftjoins as $join) {
389 | // if ($qryJoin != "") $qryJoin .= "\n";
390 | // $qryJoin .= $join->JoinSentence;
391 |
392 | // if ($fieldsJoin != "")
393 | // $fieldsJoin .= ",\n\t";
394 | // $fieldsJoin .= $join->JoinFields;
395 | // }
396 | // }
397 |
398 | // if ($withs->Count() > 0) {
399 | // foreach($withs as $join) {
400 | // if ($qryJoin != "") $qryJoin .= "\n";
401 | // $qryJoin .= $join->JoinSentence;
402 |
403 | // if ($fieldsJoin != "")
404 | // $fieldsJoin .= ",\n\t";
405 | // $fieldsJoin .= $join->JoinFields;
406 | // }
407 | // }
408 |
409 |
410 | // SELECT
411 | $top = "";
412 | if ($this->Top > 0 && self::$ConnectionType == 'sqlserver') {
413 | $top = " TOP " . $this->Top . " ";
414 | }
415 | $distinct = ($this->UseDistinct) ? ' DISTINCT ' : '';
416 | $qrySelect = "SELECT" . $top . $distinct . "\n\t" . $joinFields = trim(str_replace(", ", ",\n\t", $this->FromDefinition->NamedNotIgnoredFields));
417 |
418 | // JOIN y WITH fields
419 | if ($fieldsJoin != "")
420 | $qrySelect .= ",\n $fieldsJoin ";
421 |
422 | // FROM
423 | $qrySelect .= "\nFROM\n\t" . $this->FromDefinition->NamedTable;
424 |
425 | // JOIN y WITH
426 | if ($qryJoin != "")
427 | $qrySelect .= "\n" . $qryJoin;
428 |
429 | // WHEREs
430 | $wheres = $this->GetWheres($this->WhereDefinitions);
431 |
432 | $whereSql = "";
433 | $bindingVars = new GenericCollection();
434 |
435 | foreach($wheres as $where) {
436 | if ($whereSql != "")
437 | $whereSql .= "\nAND\t";
438 |
439 | $whereSql .= "(" . $where->Condition . ")";
440 | $bindingVars->AddRange($where->Bindings);
441 | }
442 |
443 | if ($whereSql != "")
444 | $qrySelect .= "\nWHERE\n\t" . $whereSql;
445 |
446 | if ($this->Order != "") {
447 | $qrySelect .= "\nORDER BY\n\t" . $this->Order;
448 | }
449 |
450 | if ($this->Top > 0 && self::$ConnectionType == 'mysql') {
451 | $qrySelect .= "\nLIMIT " . $this->Top;
452 | }
453 |
454 | return (object)[
455 | "Statement" => $qrySelect,
456 | "Bindings" => $bindingVars,
457 | "FromDefinition" => $this->FromDefinition,
458 | "JoinDefinitions" => $this->JoinDefinitions,
459 | "LeftJoinDefinitions" => $this->LeftJoinDefinitions,
460 | "WithDefinitions" => $this->WithDefinitions
461 | ];
462 | }
463 |
464 | private function GetJoins(GenericCollection $joinDefinitions, EntityDefinition $mainEntityDefinition, bool $leftJoin = false) {
465 |
466 | $joins = new GenericCollection();
467 |
468 | foreach($joinDefinitions as $joinEntityDefinition) {
469 | $joins->Add($this->GetJoin($joinEntityDefinition, $mainEntityDefinition, $leftJoin));
470 | }
471 |
472 | return $joins;
473 | }
474 |
475 | private function GetJoin(EntityDefinition $joinEntityDefinition, EntityDefinition $mainEntityDefinition, bool $leftJoin = false) {
476 |
477 | // La llave primaria de la tabla referenciada
478 | $primaryKey = $mainEntityDefinition->TablePrefix . "." . $mainEntityDefinition->Key;
479 | $primaryKeyName = $joinEntityDefinition->KeyName;
480 |
481 | // La llave foránea de la tabla principal
482 | //$foreignProperty = $joinEntityDefinition->Properties[$joinEntityDefinition->KeyName];
483 | $foreignKey = $joinEntityDefinition->TablePrefix . "." . $mainEntityDefinition->Key;
484 | if (isset($joinEntityDefinition->CustomForeignKey) && $joinEntityDefinition->CustomForeignKey != '') {
485 |
486 | // tiene punto de separacion con una entidad?
487 | if (strlen($joinEntityDefinition->CustomForeignKey) != strlen( str_replace('.', '', $joinEntityDefinition->CustomForeignKey))) {
488 | $foreignKey = $joinEntityDefinition->CustomForeignKey;
489 | }
490 | else {
491 | // no tiene... asignamos la entidad principal
492 | $foreignKey = $mainEntityDefinition->TablePrefix . "." . $joinEntityDefinition->CustomForeignKey;
493 | }
494 | }
495 | else {
496 | //$foreignProperty = $mainEntityDefinition->Properties[$primaryKeyName];
497 | //$foreignKey = $mainEntityDefinition->TablePrefix . "." . $foreignProperty->ColumnName;
498 | }
499 |
500 | if (isset($joinEntityDefinition->CustomParentKey) && $joinEntityDefinition->CustomParentKey != '') {
501 | // tiene punto de separacion con una entidad?
502 | if (strlen($joinEntityDefinition->CustomParentKey) != strlen( str_replace('.', '', $joinEntityDefinition->CustomParentKey))) {
503 | $primaryKey = $joinEntityDefinition->CustomParentKey;
504 | }
505 | else {
506 | // no tiene... asignamos la entidad principal
507 | $primaryKey = $joinEntityDefinition->TablePrefix . "." . $joinEntityDefinition->CustomParentKey;
508 | }
509 | }
510 |
511 |
512 | // $foreignProperty->ColumnName;
513 | //$foreignKey = $mainEntityDefinition->Properties[$joinEntityDefinition->KeyName]->ColumnName;
514 |
515 | // Obtener Campos, se debe ignorar el campo utilizado en la llave foranea,
516 | // dado que la entidad principal ya la está incluyendo
517 | $fields = $joinEntityDefinition->NamedRenamedNotIgnoredFields;
518 | // $fields = str_replace($joinEntityDefinition->TablePrefix . "." . $mainEntityDefinition->Key . " AS \"" . $joinEntityDefinition->TablePrefix . "." . $mainEntityDefinition->KeyName . "\", ", "", $fields);
519 | // $fields = str_replace($joinEntityDefinition->TablePrefix . "." . $mainEntityDefinition->Key . " AS \"" . $joinEntityDefinition->TablePrefix . "." . $mainEntityDefinition->KeyName . "\",", "", $fields);
520 | // $fields = str_replace(", ". $joinEntityDefinition->TablePrefix . "." . $mainEntityDefinition->Key . " AS \"" . $joinEntityDefinition->TablePrefix . "." . $mainEntityDefinition->KeyName . "\"", "", $fields);
521 |
522 | $joinFields = trim(str_replace(", ", ",\n\t", $fields));
523 |
524 | $reservedWord = ($leftJoin) ? 'LEFT JOIN' : 'JOIN';
525 |
526 | $joinSentence = "$reservedWord\t" . str_pad($joinEntityDefinition->NamedTable, 20, " ") . " ON "
527 | . $foreignKey . " = "
528 | . $primaryKey;
529 |
530 | return (object)[
531 | "Entity" => $joinEntityDefinition->Entity,
532 | "JoinFields" => $joinFields,
533 | "JoinSentence" => $joinSentence
534 | ];
535 | }
536 |
537 | private function GetWiths(GenericCollection $withDefinitions, EntityDefinition $mainEntityDefinition) {
538 |
539 | $withs = new GenericCollection();
540 |
541 | foreach($withDefinitions as $withEntityDefinition) {
542 | $withs->Add($this->GetWith($withEntityDefinition, $mainEntityDefinition));
543 | }
544 |
545 | return $withs;
546 | }
547 |
548 | private function GetWith(EntityDefinition $withEntityDefinition, EntityDefinition $mainEntityDefinition) {
549 |
550 | $primaryKey = $mainEntityDefinition->TablePrefix . "." . $withEntityDefinition->Key;
551 | $primaryKeyName = $withEntityDefinition->KeyName;
552 |
553 | // La llave foránea de la tabla principal
554 | //$foreignProperty = $joinEntityDefinition->Properties[$joinEntityDefinition->KeyName];
555 | $foreignKey = $withEntityDefinition->TablePrefix . "." . $withEntityDefinition->Key;
556 | if (isset($withEntityDefinition->CustomForeignKey) && $withEntityDefinition->CustomForeignKey != '') {
557 |
558 | // tiene punto de separacion con una entidad?
559 | if (strlen($withEntityDefinition->CustomForeignKey) != strlen( str_replace('.', '', $withEntityDefinition->CustomForeignKey))) {
560 | $foreignKey = $withEntityDefinition->CustomForeignKey;
561 | }
562 | else {
563 | // no tiene... asignamos la entidad principal
564 | $foreignKey = $mainEntityDefinition->TablePrefix . "." . $withEntityDefinition->CustomForeignKey;
565 | }
566 | }
567 | else {
568 | //$foreignProperty = $mainEntityDefinition->Properties[$primaryKeyName];
569 | //$foreignKey = $mainEntityDefinition->TablePrefix . "." . $foreignProperty->ColumnName;
570 | }
571 |
572 | if (isset($withEntityDefinition->CustomParentKey) && $withEntityDefinition->CustomParentKey != '') {
573 | // tiene punto de separacion con una entidad?
574 | if (strlen($withEntityDefinition->CustomParentKey) != strlen( str_replace('.', '', $withEntityDefinition->CustomParentKey))) {
575 | $primaryKey = $withEntityDefinition->CustomParentKey;
576 | }
577 | else {
578 | // no tiene... asignamos la entidad principal
579 | $primaryKey = $withEntityDefinition->TablePrefix . "." . $withEntityDefinition->CustomParentKey;
580 | }
581 | }
582 |
583 |
584 | // Obtener Campos, se debe ignorar el campo utilizado en la llave foranea,
585 | // dado que la entidad principal ya la está incluyendo
586 | $fields = $withEntityDefinition->NamedRenamedNotIgnoredFields;
587 |
588 | $joinFields = trim(str_replace(", ", ",\n\t", $fields));
589 |
590 | $joinSentence = (($withEntityDefinition->LeftWith) ? 'LEFT ' : '') . "JOIN\t" . str_pad($withEntityDefinition->NamedTable, 20, " ") . " ON "
591 | . $foreignKey . " = "
592 | . $primaryKey;
593 |
594 | return (object)[
595 | "Entity" => $withEntityDefinition->Entity,
596 | "JoinFields" => $joinFields,
597 | "JoinSentence" => $joinSentence
598 | ];
599 | }
600 |
601 | private function GetWheres(GenericCollection $whereDefinitions) {
602 |
603 | $wheres = array();
604 |
605 | $startFrom = 0;
606 | foreach($whereDefinitions as $whereDefinition) {
607 |
608 | $where = $this->GetWhere($whereDefinition, $startFrom);
609 | $startFrom += count($where->Bindings);
610 |
611 | array_push($wheres, $where);
612 | }
613 |
614 | return $wheres;
615 | }
616 |
617 | private function GetWhere($whereDefinition, $startFrom = 0) {
618 |
619 | // Condition, Parameters
620 | // ->Where('Mantencion.IdTipoEstado = ? AND Mantencion.FechaInicioProgramada BETWEEN ? AND ?', 1, $dtInicio, $dtFin)
621 | $where = $whereDefinition->Condition;
622 |
623 | // Primero obtenemos todos los elementos que se requieren reemplazar,
624 | // es decir TablePrefix.Name se debe reemplazar por TablePrefix.ColumnName
625 | // -------------------------------------------------------------------------------------
626 | // FROM
627 | $where = $this->ReplaceProperties($this->FromDefinition->Properties, $this->FromDefinition->TablePrefix, $where);
628 |
629 | // JOINS
630 | foreach($this->JoinDefinitions as $joinDefinition) {
631 | $where = $this->ReplaceProperties($joinDefinition->Properties, $joinDefinition->TablePrefix, $where);
632 | }
633 |
634 | // Withs
635 | foreach($this->WithDefinitions as $withDefinition) {
636 | $where = $this->ReplaceProperties($withDefinition->Properties, $withDefinition->TablePrefix, $where);
637 | }
638 |
639 | // Ahora, generamos los bindings
640 | $cantidadPlaceholder = substr_count($where, "?");
641 | $cantidadParametros = count($whereDefinition->Parameters);
642 | $bindings = array();
643 |
644 | for ($i=$startFrom; ( ($i-$startFrom) < $cantidadPlaceholder) && ( ($i-$startFrom) < $cantidadParametros); $i++) {
645 | $bindingVar = ":var" . $i;
646 | // reemplazamos el placeholder
647 | $where = $this->str_first_replace("?", $bindingVar, $where);
648 | // agregamos la variable binding
649 | array_push($bindings, (object)["BindingVariable" => $bindingVar, "BindingValue" => $whereDefinition->Parameters[$i-$startFrom]]);
650 | }
651 |
652 | // Resultado
653 | return (object)["Condition" => $where, "Bindings" => $bindings];
654 | }
655 |
656 | private function str_first_replace($search, $replace, $subject)
657 | {
658 | return ($pos=strpos($subject, $search))!==FALSE?substr_replace($subject, $replace, $pos, strlen($search)):$subject;
659 | }
660 |
661 | private function ReplaceProperties(array $properties, string $tablePrefix, string $whereCondition) {
662 |
663 | foreach($properties as $property) {
664 | $whereCondition = str_replace(
665 | $tablePrefix . "." . $property->Name,
666 | $tablePrefix . "." . $property->ColumnName,
667 | $whereCondition
668 | );
669 |
670 | }
671 |
672 | return $whereCondition;
673 | }
674 |
675 | /* LO QUE QUEREMOS LOGRAR:
676 |
677 | $qry = (new Queryable())
678 | ->From(Mantencion::class)
679 | ->Join(TipoEstado::class)
680 | ->With(Actividad:class)
681 | ->With(JefeTurno::class)
682 | ->Where('Mantencion.IdTipoEstado = ? AND Mantencion.FechaInicioProgramada BETWEEN ? AND ?', 1, $dtInicio, $dtFin)
683 | ->Build();
684 |
685 | */
686 |
687 | }
--------------------------------------------------------------------------------
Total de líneas: 687
================================================================================
================================================================================
ARCHIVO #124: src/Dates/Date.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Dates/Date.php
Tamaño: 20.25 KB
--------------------------------------------------------------------------------
1 | 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30, 7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31];
22 | private $_meses = [
23 | 1 => 'Enero',
24 | 2 => 'Febrero',
25 | 3 => 'Marzo',
26 | 4 => 'Abril',
27 | 5 => 'Mayo',
28 | 6 => 'Junio',
29 | 7 => 'Julio',
30 | 8 => 'Agosto',
31 | 9 => 'Septiembre',
32 | 10 => 'Octubre',
33 | 11 => 'Noviembre',
34 | 12 => 'Diciembre'
35 | ];
36 |
37 |
38 |
39 | /// Obtiene las cantidad de dias que tiene el mes según el año
40 | public function DiasMes(int $mes, int $año)
41 | {
42 |
43 | if ($mes < 1 || $mes > 12)
44 | return 0;
45 |
46 | if ($mes == 2) { // febrero
47 | $mod_año = Modulo::Calc($año, 4);
48 |
49 | return ($mod_año->Resto == 0) ? $this->_diasMes[$mes] + 1 : $this->_diasMes[$mes];
50 | } else {
51 | return $this->_diasMes[$mes];
52 | }
53 | }
54 |
55 | public function MesDelAño(?DateTime $fecha)
56 | {
57 | if(!isset($fecha))
58 | $fecha = $this;
59 |
60 | $mes = (int)$fecha->format('n');
61 | return $this->_meses[$mes];
62 | }
63 |
64 | public function WeekDay($SundayStartsOnZero = false)
65 | {
66 |
67 | $diaSemana = $this->format('w') * 1;
68 | $diaSemana = $diaSemana + (($SundayStartsOnZero) ? 0 : 1);
69 |
70 | return $diaSemana;
71 | }
72 |
73 | public static function FromNumericDate($idTurno)
74 | {
75 | $fecha = substr($idTurno, 0, 4)
76 | . '-' . substr($idTurno, 4, 2)
77 | . '-' . substr($idTurno, 6, 2)
78 | . ' ' . substr($idTurno, 8, 2)
79 | . ':' . substr($idTurno, 10, 2);
80 |
81 | return new self($fecha);
82 | }
83 |
84 | public static function Hoy(?int $offset = null)
85 | {
86 | if ($offset != null) {
87 | $fecha = new self('now', 'UTC');
88 | $intervalo = 'PT' . abs($offset) . 'H';
89 |
90 | if ($offset > 0)
91 | $fecha->add(new DateInterval($intervalo));
92 | else
93 | $fecha->sub(new DateInterval($intervalo));
94 | // Se instancia de nuevo para que se mantenga la zona horaria por defecto
95 | return new self($fecha->format('Y-m-d H:i:s'));
96 | } else
97 | return new self();
98 | }
99 |
100 |
101 | public function __construct($time = 'now', $timezone = 'America/Santiago')
102 | {
103 | parent::__construct($time, new \DateTimeZone($timezone));
104 | }
105 |
106 | public function __toString()
107 | {
108 | return $this->format('Y-m-d H:i:s');
109 | }
110 |
111 | public static function IsValidDateFast(string $dateString, string $format = 'Y-m-d'): bool
112 | {
113 | // Suprimimos los errores para no generar warnings en cada iteración.
114 | // Esto es solo para rendimiento, la lógica sigue siendo la misma.
115 | $date = @DateTime::createFromFormat($format, $dateString);
116 |
117 | // Asegurarse de que se creó un objeto DateTime y que el string original
118 | // coincide con el string formateado del objeto (para evitar desbordamientos).
119 | return $date && $date->format($format) === $dateString;
120 | }
121 |
122 | /**
123 | * Convierte un número serial de fecha de Excel a un timestamp Unix en PHP.
124 | * Esta función es la misma que te proporcioné anteriormente.
125 | *
126 | * @param float $excelDate El número serial de fecha de Excel (puede tener decimales para la hora).
127 | * @return int|false Un timestamp Unix (entero) o false si la entrada no es válida.
128 | */
129 | private static function ExcelSerialDateToUnixTimestamp(float $excelDate)
130 | {
131 | if ($excelDate < 1) {
132 | return false;
133 | }
134 |
135 | $daysOffset = 25569;
136 |
137 | if ($excelDate < 61) {
138 | $daysOffset--;
139 | }
140 |
141 | $unixDays = $excelDate - $daysOffset;
142 | $timestamp = round($unixDays * 86400);
143 |
144 | // Para evitar errores con timestamps fuera de rango en sistemas de 32 bits
145 | if ($timestamp > PHP_INT_MAX || $timestamp < ~PHP_INT_MAX) { // ~PHP_INT_MAX es el mínimo negativo
146 | return false;
147 | }
148 |
149 | return (int) $timestamp;
150 | }
151 |
152 | public static function ConvertExcelDateToYMD(float $excelDate)
153 | {
154 | $timestamp = self::ExcelSerialDateToUnixTimestamp($excelDate);
155 | if ($timestamp === false) {
156 | return false;
157 | }
158 | return date('Y-m-d', $timestamp);
159 | }
160 |
161 | public static function ConvertExcelDateTimeToYMDHIS(float $excelDate)
162 | {
163 | $timestamp = self::ExcelSerialDateToUnixTimestamp($excelDate);
164 | if ($timestamp === false) {
165 | return false;
166 | }
167 | return date('Y-m-d H:i:s', $timestamp);
168 | }
169 |
170 | public function addInterval(
171 | int $years = 0,
172 | int $months = 0,
173 | int $days = 0,
174 | int $hours = 0,
175 | int $minutes = 0,
176 | int $seconds = 0
177 | ) {
178 |
179 | // Valores actuales de la fecha
180 | // como intervalo de tiempos
181 | $fechaActual = new Interval(
182 | Years: $this->format('Y') * 1,
183 | Months: $this->format('m') * 1,
184 | Days: $this->format('d') * 1,
185 | Hours: $this->format('H') * 1,
186 | Minutes: $this->format('i') * 1,
187 | Seconds: $this->format('s') * 1
188 | );
189 |
190 | // Intervalo a agregar
191 | $add = new Interval(
192 | Years: $years,
193 | Months: $months,
194 | Days: $days,
195 | Hours: $hours,
196 | Minutes: $minutes,
197 | Seconds: $seconds
198 | );
199 |
200 |
201 | // Regularizar los elementos a agregar desde los segundos hacia adelante
202 | //
203 |
204 | // Segundos a agregar
205 | if ($add->Seconds > 0) {
206 |
207 | // agregar los segundos solicitados
208 | $fechaActual->Seconds += $add->Seconds;
209 |
210 | // Si pasa de 60 segundos, aumentar los minutos a agregar y sólo dejar los segundos que restan
211 | if ($fechaActual->Seconds >= 60) {
212 | $modulo = Modulo::Calc($fechaActual->Seconds, 60);
213 |
214 | $add->Minutes += $modulo->Cociente;
215 | $fechaActual->Seconds = $modulo->Resto;
216 | }
217 | }
218 |
219 | // Minutos a agregar
220 | if ($add->Minutes > 0) {
221 |
222 | // agregar los minutos solicitados
223 | $fechaActual->Minutes += $add->Minutes;
224 |
225 | // Si pasa de 60 minutos, aumentar las horas a agregar
226 | if ($fechaActual->Minutes >= 60) {
227 | $modulo = Modulo::Calc($fechaActual->Minutes, 60);
228 |
229 | $add->Hours += $modulo->Cociente;
230 | $fechaActual->Minutes = $modulo->Resto;
231 | }
232 | }
233 |
234 | // Horas a agregar
235 | if ($add->Hours > 0) {
236 |
237 | // Agregar las horas solicitadas
238 | $fechaActual->Hours += $add->Hours;
239 |
240 | // Si pasa de 24 horas, aumentar los días a agregar
241 | if ($fechaActual->Hours >= 24) {
242 |
243 | $modulo = Modulo::Calc($fechaActual->Hours, 24);
244 |
245 | $add->Days += $modulo->Cociente;
246 | $fechaActual->Hours = $modulo->Resto;
247 | }
248 | }
249 |
250 | // Dias a agregar
251 | // Obs: tomar en cuenta al pasar por febrero, si el año es bisiesto
252 | if ($add->Days > 0) {
253 |
254 | $currentDay = $this->format('d') * 1;
255 | $currentMonth = $this->format('m') * 1;
256 | $currentYear = $this->format('Y') * 1;
257 |
258 | // dias a agregar
259 | $remanente = $add->Days;
260 |
261 | // agregar dias mes por mes
262 | while ($remanente > 0) {
263 |
264 | // obtener los dias disponibles del mes actual
265 | $disponible = $this->DiasMes($currentMonth, $currentYear) - $currentDay + 1;
266 |
267 | if ($disponible > $remanente) {
268 | // terminamos
269 | $currentDay += $remanente;
270 | $remanente = 0;
271 | } else {
272 | $currentDay = 1;
273 | $currentMonth++;
274 |
275 | if ($currentMonth > 12) {
276 | $currentMonth = 1;
277 | $currentYear++;
278 | }
279 |
280 | $remanente = $remanente - $disponible;
281 | }
282 | }
283 |
284 | $fechaActual->Days = $currentDay;
285 | $fechaActual->Months = $currentMonth;
286 | $fechaActual->Years = $currentYear;
287 | }
288 |
289 | // Meses a agregar
290 | // Obs: la fecha actual ya se encuentra actualizada en la pasada de los días, si se agregó alguno
291 | if ($add->Months > 0) {
292 | // se agregan meses, tener cuidado en la cantidad de días que tiene cada uno
293 | $remanente = $add->Months;
294 |
295 | while ($remanente > 0) {
296 |
297 | $remanente--;
298 |
299 | // agregamos 1 mes
300 | if ($fechaActual->Months == 12) { // diciembre tiene 31 días y enero también, así que agregamos 1 al año y dejamos en enero el mes actual
301 | $fechaActual->Months = 1;
302 | $fechaActual->Years++;
303 | } else {
304 | // verificamos si en el siguiente mes, se puede tener el mismo día actual
305 | $diasMesSiguiente = $this->DiasMes($fechaActual->Months + 1, $fechaActual->Years);
306 |
307 | // Tenemos el día actual en el siguiente mes, entonces sólo aumentamos el mes
308 | if ($fechaActual->Days <= $diasMesSiguiente) {
309 | $fechaActual->Months++;
310 | }
311 | // Si no tenemos el día en el siguiente mes, tenemos que dejar el día según
312 | // la diferencia y hacer que el bucle se ejecute de nuevo para agregar el mes
313 | else {
314 | $fechaActual->Days = $fechaActual->Days - $diasMesSiguiente;
315 | // aseguramos una ejecución adicional del ciclo para que agregue el mes
316 | $remanente++;
317 | }
318 | }
319 | }
320 | }
321 |
322 | // Año a agregar
323 | // Obs: si estamos en año bisiesto y la fecha actual es 29-Febrero, se agrega el año pero se cambia al 1-Marzo, dado que el siguiente año no es bisiesto
324 | if ($add->Years > 0) {
325 |
326 | $remanente = $add->Years;
327 |
328 | while ($remanente > 0) {
329 |
330 | if ($fechaActual->Months == 2 && $fechaActual->Days == 29) {
331 | $fechaActual->Years++;
332 | $fechaActual->Months = 3;
333 | $fechaActual->Days = 1;
334 | } else {
335 | $fechaActual->Years++;
336 | }
337 |
338 | $remanente--;
339 | }
340 | }
341 |
342 | return new Date(
343 | $fechaActual->Years . '-' .
344 | $fechaActual->Months . '-' .
345 | $fechaActual->Days . ' ' .
346 | $fechaActual->Hours . ':' .
347 | $fechaActual->Minutes . ':' .
348 | $fechaActual->Seconds
349 | );
350 | }
351 |
352 |
353 | public function subInterval(
354 | int $years = 0,
355 | int $months = 0,
356 | int $days = 0,
357 | int $hours = 0,
358 | int $minutes = 0,
359 | int $seconds = 0
360 | ) {
361 |
362 | // Valores actuales de la fecha
363 | // como intervalo de tiempos
364 | $fechaActual = new Interval(
365 | Years: $this->format('Y') * 1,
366 | Months: $this->format('m') * 1,
367 | Days: $this->format('d') * 1,
368 | Hours: $this->format('H') * 1,
369 | Minutes: $this->format('i') * 1,
370 | Seconds: $this->format('s') * 1
371 | );
372 |
373 | // Intervalo a sustraer
374 | $sub = new Interval(
375 | Years: $years,
376 | Months: $months,
377 | Days: $days,
378 | Hours: $hours,
379 | Minutes: $minutes,
380 | Seconds: $seconds
381 | );
382 |
383 |
384 | // Regularizar los elementos a sustraer desde los segundos hacia adelante
385 | //
386 |
387 | // Segundos a sustraer
388 | if ($sub->Seconds > 0) {
389 |
390 | // sustraer los segundos solicitados
391 | $fechaActual->Seconds -= $sub->Seconds;
392 |
393 | // Si baja de 0 segundos, sustraer los minutos a y sólo dejar los segundos que restan
394 | if ($fechaActual->Seconds < 0) {
395 | $modulo = Modulo::Calc(abs($fechaActual->Seconds) + 60, 60);
396 |
397 | $sub->Minutes += $modulo->Cociente;
398 | $fechaActual->Seconds = 60 - $modulo->Resto;
399 | }
400 | }
401 |
402 |
403 | // Minutos a agregar
404 | if ($sub->Minutes > 0) {
405 |
406 | // agregar los minutos solicitados
407 | $fechaActual->Minutes -= $sub->Minutes;
408 |
409 | // Si baja de 0 minutos, sustraer las horas
410 | if ($fechaActual->Minutes < 0) {
411 | $modulo = Modulo::Calc(abs($fechaActual->Minutes) + 60, 60);
412 |
413 | $sub->Hours += $modulo->Cociente;
414 | $fechaActual->Minutes = 60 - $modulo->Resto;
415 | }
416 | }
417 |
418 |
419 | // Horas a agregar
420 | if ($sub->Hours > 0) {
421 |
422 | // Agregar las horas solicitadas
423 | $fechaActual->Hours -= $sub->Hours;
424 |
425 | // Si pasa de 24 horas, aumentar los días a agregar
426 | if ($fechaActual->Hours < 0) {
427 |
428 | $modulo = Modulo::Calc(abs($fechaActual->Hours) + 24, 24);
429 |
430 | $sub->Days += $modulo->Cociente;
431 | $fechaActual->Hours = 24 - $modulo->Resto;
432 | }
433 | }
434 |
435 |
436 | // Dias a sustraer
437 | // Obs: tomar en cuenta al pasar por febrero, si el año es bisiesto
438 | if ($sub->Days > 0) {
439 |
440 | // dias a sustraer
441 | $remanente = $sub->Days;
442 |
443 | // sustraer dias mes por mes
444 | while ($remanente > 0) {
445 |
446 | if ($remanente < $fechaActual->Days) {
447 | // terminamos
448 | $fechaActual->Days -= $remanente;
449 | $remanente = 0;
450 | } else {
451 |
452 | $remanente -= $fechaActual->Days;
453 |
454 | // quitar los dias y dejar en el ultimo dia del mes anterior
455 | if ($fechaActual->Months == 1) {
456 | $fechaActual->Months = 12;
457 | $fechaActual->Years--;
458 | $fechaActual->Days = 31;
459 | } else {
460 | $fechaActual->Months--;
461 | $fechaActual->Days = $this->DiasMes($fechaActual->Months, $fechaActual->Years);
462 | }
463 | }
464 | }
465 | }
466 |
467 |
468 | // Meses a sustraer
469 | // Obs: la fecha actual ya se encuentra actualizada en la pasada de los días, si se sustrajo alguno
470 | if ($sub->Months > 0) {
471 |
472 | // se sustraen meses, tener cuidado en la cantidad de días que tiene cada uno
473 | $remanente = $sub->Months;
474 |
475 | while ($remanente > 0) {
476 |
477 | $remanente--;
478 |
479 | // sustraemos 1 mes
480 | if ($fechaActual->Months == 1) { // diciembre tiene 31 días y enero también, así que sustraemos 1 al año y dejamos en diciembre el mes actual
481 | $fechaActual->Months = 12;
482 | $fechaActual->Years--;
483 | } else {
484 | // verificamos si en el mes anterior, se puede tener el mismo día actual
485 | $diasMesAnterior = $this->DiasMes($fechaActual->Months - 1, $fechaActual->Years);
486 |
487 | // Tenemos el día actual en el mes anterior, entonces sólo sustraemos el mes
488 | if ($fechaActual->Days <= $diasMesAnterior) {
489 | $fechaActual->Months--;
490 | }
491 | // Si no tenemos el día en el mes anterior, esteblecemos
492 | // el dia como el maximo dia perimitido del mes anterior
493 | else {
494 | $fechaActual->Months--;
495 | $fechaActual->Days = $diasMesAnterior;
496 | }
497 | }
498 | }
499 | }
500 |
501 |
502 |
503 | // Año a sustraer
504 | // Obs: si estamos en año bisiesto y la fecha actual es 29-Febrero, se sustrae el año pero se cambia al 1-Marzo, dado que el año anterior no es bisiesto
505 | if ($sub->Years > 0) {
506 |
507 | $remanente = $sub->Years;
508 |
509 | while ($remanente > 0) {
510 |
511 | if ($fechaActual->Months == 2 && $fechaActual->Days == 29) {
512 | $fechaActual->Years--;
513 | $fechaActual->Months = 3;
514 | $fechaActual->Days = 1;
515 | } else {
516 | $fechaActual->Years--;
517 | }
518 |
519 | $remanente--;
520 | }
521 | }
522 |
523 |
524 | return new Date(
525 | $fechaActual->Years . '-' .
526 | $fechaActual->Months . '-' .
527 | $fechaActual->Days . ' ' .
528 | $fechaActual->Hours . ':' .
529 | $fechaActual->Minutes . ':' .
530 | $fechaActual->Seconds
531 | );
532 | }
533 |
534 | public function hourDiff(Date $compareDate)
535 | {
536 |
537 | $diferencia = $this->diff($compareDate);
538 | $delta = abs(round($diferencia->days * 24 + $diferencia->h + ($diferencia->i / 60) + ($diferencia->s / 3600), 2));
539 |
540 | if ($diferencia->invert == 0) { // $tarea->Display->DtInicioReal < $tarea->Display->DtInicioTarea) {
541 | $delta = $delta * -1;
542 | }
543 |
544 | return $delta;
545 | }
546 |
547 | public static function ObtenerDiferenciaTiempo(?string $fechaInicio = null, ?string $fechaFin = null): string {
548 |
549 | if (!isset($fechaInicio) || $fechaInicio == "" || !isset($fechaFin) || $fechaFin == "") {
550 | return " ";
551 | }
552 |
553 | return self::ObtenerDiferenciaTiempoFromDate(
554 | new DateTime($fechaInicio),
555 | new DateTime($fechaFin)
556 | );
557 | }
558 |
559 | public static function ObtenerDiferenciaTiempoFromDate(?DateTime $fechaInicio = null, ?DateTime $fechaFin = null): string {
560 |
561 | if (!isset($fechaInicio) || !isset($fechaFin)) {
562 | return " ";
563 | }
564 |
565 | // Asegurarse de que fechaInicio sea siempre la más antigua
566 | if ($fechaInicio > $fechaFin) {
567 | $temp = $fechaInicio;
568 | $fechaInicio = $fechaFin;
569 | $fechaFin = $temp;
570 | }
571 |
572 | $intervalo = $fechaInicio->diff($fechaFin);
573 |
574 | // Calcular la diferencia total en segundos y minutos para facilitar las comparaciones
575 | $segundosTotales = $intervalo->days * 86400 + $intervalo->h * 3600 + $intervalo->i * 60 + $intervalo->s;
576 | $minutosTotales = floor($segundosTotales / 60);
577 |
578 | // Condición: Menor a 1 minuto
579 | if ($segundosTotales < 60) {
580 | return $segundosTotales . " segs.";
581 | }
582 |
583 | // Condición: Mayor o igual a 1 min pero menor a 10 min
584 | if ($minutosTotales < 10) {
585 | // Para obtener un decimal en minutos, calculamos directamente desde segundos
586 | $minutosConDecimal = round($segundosTotales / 60, 1);
587 | return $minutosConDecimal . " mins";
588 | }
589 |
590 | // Condición: Mayor o igual a 10 min y menor a 1 hora (60 minutos)
591 | // Usamos $minutosTotales para asegurar que no incluya segundos si la condición es estricta para minutos enteros.
592 | if ($minutosTotales < 60) {
593 | return $minutosTotales . " minutos";
594 | }
595 |
596 | // Condición: Mayor a 1 hora pero menor o igual a 61 minutos
597 | // Aquí parece haber una pequeña confusión en la descripción "menor o igual a 61 minutos"
598 | // para una condición "mayor a 1 hora".
599 | // Interpretando como: "Si es exactamente 1 hora, y hasta 1 hora y 1 minuto (61 minutos en total)"
600 | // Si la intención es "si el resultado es 1 hora y algunos segundos, pero el total no excede 61 minutos",
601 | // entonces esta condición se superpondría con la anterior.
602 | // La interpretación más lógica para "Mayor a 1 hora pero menor o igual a 61 minutos" sería:
603 | // Si la diferencia es de 1 hora y 0 minutos, hasta 1 hora y 1 minuto.
604 | // Usaremos los atributos del objeto DateInterval para mayor claridad.
605 | if ($intervalo->h == 1 && $intervalo->i <= 1) { // 1 hora y hasta 1 minuto
606 | return $intervalo->h . " hora"; // No considerar los minutos
607 | }
608 |
609 | // Condición: Mayor a 61 minutos (o si las condiciones anteriores no se cumplieron)
610 | // Esto cubrirá cualquier duración de 1 hora y 2 minutos en adelante, o más de 1 hora.
611 | $horas = $intervalo->h + ($intervalo->days * 24); // Asegurarse de incluir días en horas
612 | $minutosRestantes = $intervalo->i;
613 |
614 | return $horas . ($intervalo->h == 1 ? " hora " : " horas " ) . $minutosRestantes . " mins";
615 | }
616 |
617 | }
618 |
--------------------------------------------------------------------------------
Total de líneas: 618
================================================================================
================================================================================
ARCHIVO #125: src/Dates/Interval.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Dates/Interval.php
Tamaño: 2.48 KB
--------------------------------------------------------------------------------
1 | 0) {
42 | $qHoras = $horas[0];
43 | $remanente = isset($horas[1]) ? $horas[1] : '';
44 | }
45 | }
46 |
47 | // ¿vienen minutos?
48 | $qMinutos = '';
49 | if (strpos($remanente, 'M') !== false) {
50 | $minutos = explode('M', $remanente);
51 | if (is_array($minutos) && count($minutos) > 0) {
52 | $qMinutos = $minutos[0];
53 | $remanente = isset($minutos[1]) ? $minutos[1] : '';
54 | }
55 | }
56 |
57 | // ¿vienen segundos?
58 | $qSegundos = '';
59 | if (strpos($remanente, 'S') !== false) {
60 | $segundos = explode('S', $remanente);
61 | if (is_array($segundos) && count($segundos) > 0) {
62 | $qSegundos = $segundos[0];
63 | }
64 | }
65 |
66 | if (is_numeric($qHoras)) {
67 | $qHoras = round($qHoras, 0);
68 | }
69 | else {
70 | $qHoras = 0;
71 | }
72 |
73 | if (is_numeric($qMinutos)) {
74 | $qMinutos = round($qMinutos, 0);
75 | }
76 | else {
77 | $qMinutos = 0;
78 | }
79 |
80 | if (is_numeric($qSegundos)) {
81 | $qSegundos = round($qSegundos, 0);
82 | }
83 | else {
84 | $qSegundos = 0;
85 | }
86 |
87 | $interval = $qHoras . 'H' . $qMinutos . 'M' . $qSegundos . 'S';
88 |
89 | try {
90 | $result = new \DateInterval('PT' . $interval);
91 | }
92 | catch (\Exception $ex) {
93 | return null;
94 | }
95 |
96 | return $result;
97 |
98 | }
99 | }
--------------------------------------------------------------------------------
Total de líneas: 99
================================================================================
================================================================================
ARCHIVO #126: src/Document/GenericDocument.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Document/GenericDocument.php
Tamaño: 6.98 KB
--------------------------------------------------------------------------------
1 | DocumentDefinition = $documentDefinition;
27 | $this->DocumentDefinitionClass = get_class($documentDefinition);
28 | $this->DocumentClass = get_class($this);
29 |
30 | $this->Data = $data;
31 | }
32 |
33 | /**
34 | * Obtiene el enlace codificado que contiene la información de definicion de este documento
35 | */
36 | public function GetEncodedLink() {
37 |
38 | $params = get_object_vars($this->DocumentDefinition);
39 |
40 | // Recorrer las propiedades y los valores
41 | $link = '';
42 | foreach($params as $prop => $value) {
43 | if ($link != '') {
44 | $link .= ',';
45 | }
46 |
47 | $link .= $prop . "=" . trim($value);
48 | }
49 |
50 | return Encoder::Instance()->Encode($link);
51 | }
52 |
53 | /**
54 | * Agrega una clase al diccionario de tipos
55 | * Esto permite generar el tipo correcto desde el link codificado
56 | *
57 | * @param string $documentClassname
58 | * @param string $documentDefinitionclassName
59 | * @param string $className
60 | */
61 | public static function AddToDictionary($documentType, $documentClassname, $documentDefinitionclassName) {
62 | self::$DocumentTypeDictionary[$documentType] = [$documentClassname, $documentDefinitionclassName];
63 | }
64 |
65 | /**
66 | * Retorna un objeto anónimo con los valores encontrados en el link
67 | *
68 | * @param string $encodedLink
69 | *
70 | * @return GenericDocument
71 | */
72 | public static function NewFromEncodedLink($encodedLink) {
73 |
74 | $link = Encoder::Instance()->Decode($encodedLink);
75 |
76 | // Crear un arreglo con los parámetros
77 | $paramList = array();
78 | $params = explode(',', $link);
79 |
80 | foreach($params as $keypar) {
81 | $par = explode('=', $keypar);
82 |
83 | if (isset($par[0]) && isset($par[1])) {
84 | $paramList[$par[0]] = $par[1] == '' ? null : $par[1];
85 | }
86 | }
87 |
88 | // Crear un nuevo objeto para la definición del documento
89 | //
90 | $documentDefinition = null;
91 |
92 | if (isset($paramList['DocumentType'])) {
93 |
94 | // Buscar el objeto en el diccionario
95 | if (isset(self::$DocumentTypeDictionary[$paramList['DocumentType']])) {
96 |
97 | $documentDeclaration = self::$DocumentTypeDictionary[$paramList['DocumentType']];
98 |
99 | $documentClassName = $documentDeclaration[0];
100 | $definitionClassName = $documentDeclaration[1];
101 |
102 | $documentDefinition = new $definitionClassName($paramList);
103 |
104 | if (isset($paramList['Filename'])) {
105 | $documentDefinition->Filename = $paramList['Filename'];
106 | }
107 |
108 | $document = new $documentClassName($documentDefinition);
109 | }
110 | }
111 | else {
112 | throw new \Exception('El tipo de documento no ha sido definido');
113 | }
114 |
115 | return $document;
116 | }
117 |
118 | public static function GenerateRandomFilename(string $extension = null, $prefix = '', $longFilename = false) {
119 |
120 | $filename = uniqid($prefix, $longFilename);
121 |
122 | if (isset($extension)) {
123 | $filename .= '.' . $extension;
124 | }
125 |
126 | return $filename;
127 | }
128 |
129 | public function SetContent($data) {
130 | $this->Data = $data;
131 | }
132 |
133 | public function GetDocumentDefinition() {
134 |
135 | return $this->DocumentDefinition;
136 |
137 | }
138 |
139 | /**
140 | * Obtiene la carpeta donde se almacenará el documento, según lógica basada en el DocumentDefinition
141 | */
142 | abstract function GetFolder();
143 |
144 | /**
145 | * Obtiene el nombre del archivo
146 | */
147 | abstract function GetFilename();
148 |
149 | /**
150 | * Obtiene la ruta del archivo en formato URL
151 | */
152 | abstract function GetUrl();
153 |
154 | abstract function GetHttpUrl();
155 |
156 |
157 | public function GetPath() {
158 |
159 | // Obtener la carpeta de almacenamiento del archivo
160 | //
161 | $folderpath = $this->GetFolder();
162 |
163 | // Obtener el nombre del archivo
164 | //
165 | $filename = $this->GetFilename();
166 |
167 | // Generar la ruta del archivo
168 | //
169 | $filepath = $folderpath . '/' . $filename;
170 |
171 | return $filepath;
172 | }
173 |
174 |
175 |
176 | /**
177 | * Abre el archivo correspondiente al documento y retorna el contenido
178 | *
179 | */
180 | public function LoadDocument($binary = true) {
181 |
182 | // Chequear que el archivo exista
183 | //
184 | $filepath = $this->GetPath();
185 |
186 | if (file_exists($filepath)) {
187 | $file = null;
188 |
189 | if ($binary)
190 | $file = fopen($filepath, 'rb');
191 | else
192 | $file = fopen($filepath, 'r');
193 |
194 | if ($file) {
195 | $contents = fread($file, filesize($filepath));
196 | fclose($file);
197 |
198 | return $contents;
199 | }
200 |
201 | else {
202 | return null;
203 | }
204 |
205 | }
206 | else {
207 | return null;
208 | }
209 | }
210 |
211 | /**
212 | * Guarda el archivo correspondiente al documento en la ruta definida
213 | *
214 | * @param bool $sobreescribir Sobrescribir el archivo si existe
215 | * @param bool $base64Image Guardar el archivo como imagen desde un origen en base64
216 | *
217 | */
218 | public function SaveDocument($sobreescribir = false, $base64Image = false, $createFolders = true) {
219 |
220 | // Chequear que la data exista
221 | //
222 | if (!isset($this->Data) || $this->Data == '') {
223 | throw new \Exception('El documento no contiene información para guardar');
224 | }
225 |
226 | // Chequear que la carpeta de destino existe
227 | //
228 | $folderPath = $this->GetFolder($this->DocumentDefinition);
229 |
230 | if (!file_exists($folderPath)) {
231 | if ($createFolders) {
232 | mkdir($folderPath, 0775, true);
233 | }
234 | }
235 |
236 | // Chequear que el archivo NO exista
237 | //
238 | $filepath = $this->GetPath();
239 |
240 | if (file_exists($filepath) && !$sobreescribir) {
241 | throw new \Exception('El archivo ya existe');
242 | }
243 | else {
244 | if ($base64Image) {
245 | // Escribir la imagen
246 | $imageData = base64_decode($this->Data);
247 | $source = imagecreatefromstring($imageData);
248 | $rotate = imagerotate($source, 0, 0); // if want to rotate the image
249 | $imageSave = imagejpeg($rotate, $filepath, 100);
250 |
251 | imagedestroy($source);
252 | }
253 | else {
254 | file_put_contents($filepath, $this->Data);
255 | }
256 | }
257 | }
258 |
259 | }
--------------------------------------------------------------------------------
Total de líneas: 259
================================================================================
================================================================================
ARCHIVO #127: src/Document/GenericDocumentDefinition.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Document/GenericDocumentDefinition.php
Tamaño: 548 bytes
--------------------------------------------------------------------------------
1 | _Headers = getallheaders();
31 | }
32 |
33 | private static $Instance = null;
34 |
35 | protected static function Create() {
36 | return new Headers();
37 | }
38 |
39 | final protected static function GetInstance() {
40 | return self::$Instance;
41 | }
42 |
43 | final protected static function SetInstance($instance) {
44 | self::$Instance = $instance;
45 | }
46 |
47 | public function __get($key) {
48 |
49 | if (isset($this->_Headers[$key])) {
50 | return $this->_Headers[$key];
51 | }
52 | else {
53 | return '';
54 | }
55 | }
56 |
57 | public function Get($key) {
58 | if (isset($this->_Headers[$key])) {
59 | return $this->_Headers[$key];
60 | }
61 | else {
62 | return '';
63 | }
64 | }
65 | }
--------------------------------------------------------------------------------
Total de líneas: 65
================================================================================
================================================================================
ARCHIVO #131: src/Environment/Ini.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Environment/Ini.php
Tamaño: 1.28 KB
--------------------------------------------------------------------------------
1 | Name[$Name] = ini_get($Name);
39 | ini_set($Name, $Value);
40 | }
41 |
42 | public function Rollback(string $Name) {
43 | if (isset($this->Name[$Name]) && $this->Name[$Name] != null) {
44 | ini_set($Name, $this->Name[$Name]);
45 | }
46 | else {
47 | throw new \Exception('Se intenta restaurar un valor de INI no cambiado previamente');
48 | }
49 | }
50 |
51 | public function SetTimeLimit($seconds) {
52 | set_time_limit($seconds);
53 | }
54 | }
--------------------------------------------------------------------------------
Total de líneas: 54
================================================================================
================================================================================
ARCHIVO #132: src/Environment/IniEnum.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Environment/IniEnum.php
Tamaño: 553 bytes
--------------------------------------------------------------------------------
1 | debugMessage;
25 | }
26 | }
--------------------------------------------------------------------------------
Total de líneas: 26
================================================================================
================================================================================
ARCHIVO #137: src/Exceptions/BusinessException.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Exceptions/BusinessException.php
Tamaño: 2.38 KB
--------------------------------------------------------------------------------
1 | getTrace();
26 | // $debugTrace = debug_backtrace();
27 | // $calling_method = $trace[1]['function'];
28 | // $calling_class = $trace[1]['class'];
29 |
30 | if ($debugMessage == '') {
31 | switch($code) {
32 | case ExceptionCodesEnum::ERR_INVALID_PARAMETER: $debugMessage = 'El parámetro es inválido'; break;
33 | case ExceptionCodesEnum::ERR_MISSING_FILES: $debugMessage = 'No se han especificado archivos'; break;
34 | case ExceptionCodesEnum::ERR_MISSING_PARAMETER: $debugMessage = 'Falta el parámetro requerido'; break;
35 | case ExceptionCodesEnum::ERR_NO_SESSION: $debugMessage = 'No existe la sesión, o la sesión ha caducado'; break;
36 | }
37 | }
38 |
39 | if ($message == '') {
40 | $message = self::$DefaultMessage;
41 | }
42 | else {
43 | // Para el tipo de error ERROR_WITHVIEW, dejamos en manos de la función llamante el despliegue del error
44 | if ($code != ExceptionCodesEnum::ERR_WITHVIEW) {
45 | // Si la primera letra del mensaje es mayuscula, adicionamos el punto seguido y un espacio
46 | $first = substr($message, 0, 1);
47 |
48 | if (str_contains(self::$CapitalChars, $first)) {
49 | $message = '. ' . $message;
50 | }
51 | else {
52 | // caso contrario, solamente separamos con una coma
53 | $message = ', ' . $message;
54 | }
55 | $message = self::$DefaultMessage . $message;
56 | }
57 | }
58 |
59 | parent::__construct(message: $message, code: $code);
60 | }
61 |
62 | public function getDebugMessage() {
63 | return $this->debugMessage;
64 | }
65 | }
--------------------------------------------------------------------------------
Total de líneas: 65
================================================================================
================================================================================
ARCHIVO #138: src/Exceptions/ExceptionCodesEnum.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Exceptions/ExceptionCodesEnum.php
Tamaño: 866 bytes
--------------------------------------------------------------------------------
1 | Load($filepath);
21 | }
22 | }
23 |
24 | private function Load($file) {
25 |
26 | // Abrir el json
27 | $content = file_get_contents($file);
28 | $this->Json = json_decode($content, false, 512, JSON_FORCE_OBJECT);
29 |
30 | }
31 |
32 | public function IsNewEnabled($data) {
33 |
34 | $result = true; // por defecto SI
35 | $entity = $this->SearchEntity($data->Entity);
36 |
37 | if (isset($entity) && isset($entity->Definition) && $entity->Definition->NewEnabled == false) {
38 | $result = false;
39 | }
40 |
41 | return $result;
42 | }
43 |
44 | private function SearchEntity($entity) {
45 |
46 | $result = null;
47 |
48 | if (isset($this->Json) && isset($this->Json->Entities)) {
49 | $found = null;
50 | foreach($this->Json->Entities as $ent) {
51 | if ($ent->Schema == $entity->Schema && $ent->Entity == $entity->Table) {
52 | $found = $ent;
53 | break;
54 | }
55 | }
56 |
57 | if (isset($found)) {
58 | $result = $found;
59 | }
60 | }
61 |
62 | return $result;
63 | }
64 | }
--------------------------------------------------------------------------------
Total de líneas: 64
================================================================================
================================================================================
ARCHIVO #142: src/Generator/Engine.php
================================================================================
Ruta: /var/www/html/intouch/v4/framework/src/Generator/Engine.php
Tamaño: 80.64 KB
--------------------------------------------------------------------------------
1 | Dominio = $dominios[$entityDomain];
48 | }
49 | }
50 |
51 | public function Generate($overwrite = false) {
52 |
53 | $source = __DIR__;
54 | $dest = $_SERVER['OLDPWD'] . "/";
55 |
56 | $error = false;
57 |
58 | error_reporting(0);
59 |
60 | echo "\n";
61 | echo "Generación de código iniciada\n";
62 | echo "-----------------------------\n";
63 |
64 | // Obtener la lista de tablas
65 | $tablas = explode(',', $this->entityTable);
66 |
67 | // Validación de conexión
68 | $stmt = $this->ValidateConnection();
69 |
70 | if (!isset($stmt) || $stmt == null) {
71 | return false;
72 | }
73 |
74 | // Procesar las tablas
75 | foreach($tablas as $tabla) {
76 |
77 | $table = trim($tabla);
78 |
79 | $schema = $this->GetSchema($table);
80 | $validated = $this->Validate(Table: $table, Overwrite: $overwrite, Stmt: $stmt, Dest: $dest);
81 |
82 | if (!$validated)
83 | continue;
84 |
85 | // Obtener los campos de la tabla
86 | //
87 | $fields = $this->GetTableFields(Table: $table, Conn: $stmt);
88 |
89 | // Convertir los campos
90 | //
91 | $fieldContent = $this->ConvertFields($fields);
92 |
93 | // Generar los archivos
94 | //
95 | $files = [
96 | "Dto" => [
97 | "TemplatePath" => $source . '/Templates/Dto.php',
98 | "DestinationFolder" => $dest . 'Application/BLL/DataTransferObjects/' . $this->entityNamespace,
99 | "Destination" => $dest . 'Application/BLL/DataTransferObjects/' . $this->entityNamespace . '/' . $schema->Table . 'Dto.php',
100 | "Fields" => $fieldContent,
101 | "Preserve" => false
102 | ],
103 | "DtoT" => [
104 | "TemplatePath" => $source . '/Templates/DtoT.php',
105 | "DestinationFolder" => $dest . 'Application/BLL/DataTransferObjects/' . $this->entityNamespace,
106 | "Destination" => $dest . 'Application/BLL/DataTransferObjects/' . $this->entityNamespace . '/' . $schema->Table . 'DtoT.php',
107 | "Fields" => $fieldContent,
108 | "Preserve" => true
109 | ],
110 | "Svc" => [
111 | "TemplatePath" => $source . '/Templates/Svc.php',
112 | "DestinationFolder" => $dest . 'Application/BLL/Services/' . $this->entityNamespace,
113 | "Destination" => $dest . 'Application/BLL/Services/' . $this->entityNamespace . '/' . $schema->Table . 'Svc.php',
114 | "Fields" => $fieldContent,
115 | "Preserve" => false
116 | ],
117 | "SvcT" => [
118 | "TemplatePath" => $source . '/Templates/SvcT.php',
119 | "DestinationFolder" => $dest . 'Application/BLL/Services/' . $this->entityNamespace,
120 | "Destination" => $dest . 'Application/BLL/Services/' . $this->entityNamespace . '/' . $schema->Table . 'SvcT.php',
121 | "Fields" => $fieldContent,
122 | "Preserve" => true
123 | ],
124 | "Ent" => [
125 | "TemplatePath" => $source . '/Templates/Ent.php',
126 | "DestinationFolder" => $dest . 'Application/Dao/Entities/' . $this->entityNamespace,
127 | "Destination" => $dest . 'Application/Dao/Entities/' . $this->entityNamespace . '/' . $schema->Table . '.php',
128 | "Fields" => $fieldContent,
129 | "Preserve" => false
130 | ],
131 | "EntT" => [
132 | "TemplatePath" => $source . '/Templates/EntT.php',
133 | "DestinationFolder" => $dest . 'Application/Dao/Entities/' . $this->entityNamespace,
134 | "Destination" => $dest . 'Application/Dao/Entities/' . $this->entityNamespace . '/' . $schema->Table . 'T.php',
135 | "Fields" => $fieldContent,
136 | "Preserve" => true
137 | ],
138 | "Dao" => [
139 | "TemplatePath" => $source . '/Templates/Dao.php',
140 | "DestinationFolder" => $dest . 'Application/Dao/Services/' . $this->entityNamespace,
141 | "Destination" => $dest . 'Application/Dao/Services/' . $this->entityNamespace . '/' . $schema->Table . 'Dao.php',
142 | "Fields" => $fieldContent,
143 | "Preserve" => false
144 | ],
145 | "DaoT" => [
146 | "TemplatePath" => $source . '/Templates/DaoT.php',
147 | "DestinationFolder" => $dest . 'Application/Dao/Services/' . $this->entityNamespace,
148 | "Destination" => $dest . 'Application/Dao/Services/' . $this->entityNamespace . '/' . $schema->Table . 'DaoT.php',
149 | "Fields" => $fieldContent,
150 | "Preserve" => true
151 | ]
152 | ];
153 |
154 | // Generar los archivos
155 | //
156 | foreach($files as $file) {
157 | $this->GenerateFileFromEval(File: $file, Table: $schema, Fields: $fields, VWFields: null, ForeignKeys: null);
158 | //$this->GenerateFile(File: $file, Table: $schema);
159 | }
160 | }
161 |
162 | echo "\n";
163 | echo "-----------------------------\n";
164 |
165 | if ($error) {
166 | echo "Generación de código finalizada con error\n";
167 | }
168 | else {
169 | echo "Generación de código finalizada OK\n";
170 | }
171 |
172 | echo "\n";
173 | }
174 |
175 | public function Mantenedor($overwrite = false) {
176 |
177 | $source = __DIR__;
178 | $dest = $_SERVER['OLDPWD'] . "/";
179 |
180 | $error = false;
181 |
182 | error_reporting(0);
183 |
184 | echo "\n";
185 | echo "Generación de código iniciada\n";
186 | echo "-----------------------------\n";
187 |
188 | // Obtener la lista de tablas
189 | $tablas = explode(',', $this->entityTable);
190 |
191 | // Validación de conexión
192 | $stmt = $this->ValidateConnection();
193 |
194 | if (!isset($stmt) || $stmt == null) {
195 | return false;
196 | }
197 |
198 | // Obtener configuracion personalizada si existe
199 | $config = new Config($dest . 'Application/Configuration/generator.config.json');
200 |
201 | // Procesar las tablas
202 | foreach($tablas as $tabla) {
203 |
204 | $table = trim($tabla);
205 |
206 | $schema = $this->GetSchema($table);
207 | $validated = $this->ValidateMantenedores(Table: $table, Overwrite: $overwrite, Stmt: $stmt, Dest: $dest);
208 |
209 | if (!$validated)
210 | continue;
211 |
212 | // Obtener las llaves foraneas
213 | $foreignKeys = $this->GetSqlServerForeignKeys(Conn: $stmt);
214 |
215 | // Obtener los campos de la tabla
216 | //
217 | $fields = $this->GetTableFields(Table: $table, Conn: $stmt, ForeignKeys: $foreignKeys);
218 |
219 | // Obtener los campos de la vista
220 | //
221 | $vwName = "";
222 | if ( !(substr($schema->Table, 0, 4) == 'Tipo') ) {
223 | $names = explode('.', $table);
224 | if (count($names) == 1) {
225 | $vwName = 'VW'.$table;
226 | }
227 | else if (count($names) > 1) {
228 | $vwName = $names[0] . "." . 'VW' . $names[1];
229 | }
230 | }
231 |
232 | if ($vwName != "")
233 | $vwFields = $this->GetTableFields(Table: $vwName, Conn: $stmt);
234 | else
235 | $vwFields = $fields;
236 |
237 |
238 |
239 | // Convertir los campos
240 | //
241 | /*
242 | $dataFields = $this->JsonDataFields($fields);
243 | $jsonDataFields = $dataFields[0];
244 | $listDataFields = $dataFields[1];
245 | $use = $dataFields[2];
246 | $formRows = $dataFields[3];
247 | $formCustom = $dataFields[4];
248 |
249 | $jsonCustomButtons = $this->JsonCustomButtons($schema, $foreignKeys);
250 | $customButtons = $jsonCustomButtons[0];
251 | $customBundles = $jsonCustomButtons[1];
252 | $customFunctions = $jsonCustomButtons[2];
253 |
254 | $vwGridElements = $this->VWGridFields($vwFields, $schema->Table);
255 | $vwGridColumns = $vwGridElements[0];
256 | $vwGridButtons = $vwGridElements[1];
257 | $vwFieldsList = $vwGridElements[2];
258 | $vwFieldsCustom = $vwGridElements[3];
259 |
260 | $dtoFields = str_replace('formData.', '$registro->', $jsonDataFields);
261 | $searchFields = $this->JsonSearchFields($fields, false, $foreignKeys, $schema);
262 |
263 | $jsonSearchFields = $searchFields[0];
264 | $bindingFields = $searchFields[1];
265 | $searchRows = $searchFields[2];
266 | $searchCustom = $searchFields[3];
267 | $getbyMethods = $searchFields[4];
268 | */
269 |
270 |
271 |
272 | $filesEval = [
273 | "ApiControllerT" => [
274 | "TemplatePath" => $source . '/Templates/Mantenedores/ApiControllerT.php',
275 | "DestinationFolder" => $dest . 'Application/Controllers/Api/Mantenedores/' . $this->entityNamespace,
276 | "Destination" => $dest . 'Application/Controllers/Api/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table . 'ControllerT.php',
277 | "Preserve" => false
278 | ],
279 | "ApiController" => [
280 | "TemplatePath" => $source . '/Templates/Mantenedores/ApiController.php',
281 | "DestinationFolder" => $dest . 'Application/Controllers/Api/Mantenedores/' . $this->entityNamespace,
282 | "Destination" => $dest . 'Application/Controllers/Api/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table . 'Controller.php',
283 | "Preserve" => false
284 | ],
285 | "BusinessObjectT" => [
286 | "TemplatePath" => $source . '/Templates/Mantenedores/BusinessObjectT.php',
287 | "DestinationFolder" => $dest . 'Application/BLL/BusinessObjects/Mantenedores/' . $this->entityNamespace,
288 | "Destination" => $dest . 'Application/BLL/BusinessObjects/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table . 'BOT.php',
289 | "Preserve" => true
290 | ],
291 | "BusinessObject" => [
292 | "TemplatePath" => $source . '/Templates/Mantenedores/BusinessObject.php',
293 | "DestinationFolder" => $dest . 'Application/BLL/BusinessObjects/Mantenedores/' . $this->entityNamespace,
294 | "Destination" => $dest . 'Application/BLL/BusinessObjects/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table . 'BO.php',
295 | "Preserve" => false
296 | ],
297 | "ViewController" => [
298 | "TemplatePath" => $source . '/Templates/Mantenedores/ViewController.php',
299 | "DestinationFolder" => $dest . 'Application/Controllers/Mantenedores/' . $this->entityNamespace,
300 | "Destination" => $dest . 'Application/Controllers/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table . 'Controller.php',
301 | "Preserve" => false
302 | ],
303 | "ViewControllerT" => [
304 | "TemplatePath" => $source . '/Templates/Mantenedores/ViewControllerT.php',
305 | "DestinationFolder" => $dest . 'Application/Controllers/Mantenedores/' . $this->entityNamespace,
306 | "Destination" => $dest . 'Application/Controllers/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table . 'ControllerT.php',
307 | "Preserve" => true
308 | ],
309 | "ScriptJST" => [
310 | "TemplatePath" => $source . '/Templates/Mantenedores/ScriptJST.js',
311 | "DestinationFolder" => $dest . 'public/scripts/mantenedores/' . strtolower($this->entityNamespace),
312 | "Destination" => $dest . 'public/scripts/mantenedores/' . strtolower($this->entityNamespace) . '/' . strtolower($schema->Table) . 'T.js',
313 | "Preserve" => false
314 | ],
315 | "ScriptJS" => [
316 | "TemplatePath" => $source . '/Templates/Mantenedores/ScriptJS.js',
317 | "DestinationFolder" => $dest . 'public/scripts/mantenedores/' . strtolower($this->entityNamespace),
318 | "Destination" => $dest . 'public/scripts/mantenedores/' . strtolower($this->entityNamespace) . '/' . strtolower($schema->Table) . '.js',
319 | "Preserve" => false
320 | ],
321 | "ServiceJST" => [
322 | "TemplatePath" => $source . '/Templates/Mantenedores/ServiceJST.js',
323 | "DestinationFolder" => $dest . 'public/services/mantenedores/' . $this->entityNamespace,
324 | "Destination" => $dest . 'public/services/mantenedores/' . $this->entityNamespace . '/' . $schema->Table . 'SvcT.js',
325 | "Preserve" => false
326 | ],
327 | "ServiceJS" => [
328 | "TemplatePath" => $source . '/Templates/Mantenedores/ServiceJS.js',
329 | "DestinationFolder" => $dest . 'public/services/mantenedores/' . $this->entityNamespace,
330 | "Destination" => $dest . 'public/services/mantenedores/' . $this->entityNamespace . '/' . $schema->Table . 'Svc.js',
331 | "Preserve" => false
332 | ],
333 | "VerGridT" => [
334 | "TemplatePath" => $source . '/Templates/Mantenedores/verGridT.php',
335 | "DestinationFolder" => $dest . 'Application/Views/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table,
336 | "Destination" => $dest . 'Application/Views/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table . '/verGridT.php',
337 | "Preserve" => true
338 | ],
339 | "VerGridAsPopUpView" => [
340 | "TemplatePath" => $source . '/Templates/Mantenedores/verGridAsPopUpView.php',
341 | "DestinationFolder" => $dest . 'Application/Views/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table,
342 | "Destination" => $dest . 'Application/Views/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table . '/verGridAsPopUpView.php',
343 | "Preserve" => false
344 | ],
345 | "VerView" => [
346 | "TemplatePath" => $source . '/Templates/Mantenedores/verView.php',
347 | "DestinationFolder" => $dest . 'Application/Views/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table,
348 | "Destination" => $dest . 'Application/Views/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table . '/verView.php',
349 | "Preserve" => false,
350 | ],
351 | "VerGridView" => [
352 | "TemplatePath" => $source . '/Templates/Mantenedores/verGridView.php',
353 | "DestinationFolder" => $dest . 'Application/Views/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table,
354 | "Destination" => $dest . 'Application/Views/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table . '/verGridView.php',
355 | "Preserve" => false
356 | ],
357 | "PopUpView" => [
358 | "TemplatePath" => $source . '/Templates/Mantenedores/popupView.php',
359 | "DestinationFolder" => $dest . 'Application/Views/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table,
360 | "Destination" => $dest . 'Application/Views/Mantenedores/' . $this->entityNamespace . '/' . $schema->Table . '/popupView.php',
361 | "Preserve" => false
362 | ],
363 | ];
364 |
365 | // Ver si existe el campo IndEliminado
366 | $existeIndEliminado = false;
367 |
368 | foreach($fields as $name => $field) {
369 | if (strtolower($name) == 'indeliminado') {
370 | $existeIndEliminado = true;
371 | break;
372 | }
373 | }
374 |
375 | // Generar los archivos
376 | //
377 | foreach($filesEval as $file) {
378 | $this->GenerateFileFromEval(
379 | File: $file, Table: $schema, Fields: $fields, VWFields: $vwFields,
380 | ForeignKeys: $foreignKeys, ExisteIndEliminado: $existeIndEliminado,
381 | Config: $config
382 | );
383 | }
384 |
385 | // Actualizar los bundles
386 | if ($this->ActualizarBundles($schema->Table, $this->entityNamespace, $dest . 'Application/Configuration/bundles.config.json')) {
387 | echo "\n";
388 | echo "Se actualizaron los registros en bundles.config.json\n";
389 | echo "\n";
390 | }
391 | }
392 |
393 | echo "\n";
394 | echo "-----------------------------\n";
395 |
396 | if ($error) {
397 | echo "Generación de mantenedor finalizada con error\n";
398 | }
399 | else {
400 | echo "Generación de mantenedor finalizada OK\n";
401 | }
402 |
403 | echo "\n";
404 | }
405 |
406 | private function CargarConfiguracion($filepath) {
407 |
408 | }
409 |
410 | private function ActualizarBundles($element, $namespace, $location) {
411 |
412 | if (!file_exists($location)) {
413 | return;
414 | }
415 |
416 | $json = file_get_contents($location);
417 | $bundles = json_decode($json, true);
418 | $changed = false;
419 |
420 | if (!isset($bundles['mantenedor' . $element . 'JS'])) {
421 | $bundles['mantenedor' . $element . 'JS'] = [
422 | 'IdBundle' => 'mantenedor' . $element . 'JS',
423 | 'Tipo' => "javascript",
424 | 'Versionado' => true,
425 | 'BundleLocation' => "scripts",
426 | 'Sources' => [
427 | 0 => [
428 | "Folder" => "mantenedores/" . strtolower($namespace),
429 | "File" => strtolower($element) . '.js'
430 | ],
431 | 1 => [
432 | "Folder" => "mantenedores/" . strtolower($namespace),
433 | "File" => strtolower($element) . 'T.js'
434 | ]
435 | ]
436 | ];
437 |
438 | $changed = true;
439 | }
440 | else {
441 | $bundle = $bundles['mantenedor' . $element . 'JS'];
442 | $sources = $bundle['Sources'];
443 |
444 | $existeJS = false;
445 | $existeJST = false;
446 |
447 | foreach($sources as $source) {
448 | $existeJS = $existeJS || ($source['Folder'] == "mantenedores/" . strtolower($namespace) && $source['File'] == strtolower($element) . '.js');
449 | $existeJST = $existeJST || ($source['Folder'] == "mantenedores/" . strtolower($namespace) && $source['File'] == strtolower($element) . 'T.js');
450 | }
451 |
452 | if (!$existeJS) {
453 | $sources[] = [
454 | "Folder" => "mantenedores/" . strtolower($namespace),
455 | "File" => strtolower($element) . '.js'
456 | ];
457 |
458 | $changed = true;
459 | }
460 |
461 | if (!$existeJST) {
462 | $sources[] = [
463 | "Folder" => "mantenedores/" . strtolower($namespace),
464 | "File" => strtolower($element) . 'T.js'
465 | ];
466 |
467 | $changed = true;
468 | }
469 |
470 | $bundle['Sources'] = $sources;
471 | $bundles['mantenedor' . $element . 'JS'] = $bundle;
472 | }
473 |
474 | if ($changed) {
475 | $newJson = json_encode($bundles, JSON_UNESCAPED_SLASHES);
476 | file_put_contents($location, $newJson);
477 | return true;
478 | }
479 | else {
480 | return false;
481 | }
482 |
483 | }
484 |
485 | private function GenerateFileFromEval($File, object $Table, $Fields, $VWFields, $ForeignKeys, $ExisteIndEliminado = false, $Config= null) {
486 |
487 | $template = $File['TemplatePath'];
488 | $folder = $File['DestinationFolder'];
489 | $destination = $File['Destination'];
490 | $preserve = $File['Preserve'];
491 | $content = "";
492 |
493 | if ($preserve) {
494 | if (file_exists($destination)) {
495 | return;
496 | }
497 | }
498 |
499 | $vwTable = ( substr($Table->Table, 0, 4) == 'Tipo' ) ? $Table->Table : 'VW' . $Table->Table;
500 |
501 | // Evaluar el archivo
502 | $data = (object) [
503 | "Template" => $template,
504 | "DestinationFolder" => $destination,
505 | "Entity" => $Table,
506 | "VWEntity" => $vwTable,
507 | "Fields" => $Fields,
508 | "VWFields" => $VWFields,
509 | "ForeignKeys" => $ForeignKeys,
510 | "Namespace" => $this->entityNamespace,
511 | "EntityName" => $Table->Table,
512 | "LowerEntityName" => lcfirst($Table->Table),
513 | "ExisteIndEliminado" => $ExisteIndEliminado,
514 | "Config" => $Config
515 | ];
516 |
517 | ob_start();
518 | include( $template );
519 | $content = ob_get_contents();
520 | ob_end_clean();
521 |
522 | // Verificar si existe la carpeta de destino
523 | //
524 | if (!file_exists($folder)) {
525 | mkdir(
526 | $folder,
527 | 0775,
528 | true
529 | );
530 | }
531 |
532 | // Escribir el archivo (preservar los traits)
533 | //
534 | file_put_contents($destination, $content);
535 | //echo $content;
536 |
537 | return;
538 | }
539 |
540 | private function GenerateFile($File, object $Table) {
541 |
542 | $template = $File['TemplatePath'];
543 | $folder = $File['DestinationFolder'];
544 | $destination = $File['Destination'];
545 | $fields = $File['Fields'];
546 | $jsonDataFields = $File['JsonDataFields'];
547 | $dtoFields = $File['DtoFields'];
548 | $use = $File['Use'];
549 | $listDataFields = $File['ListDataFields'];
550 | $jsonSearchFields = $File['JsonSearchFields'];
551 | $bindingFields = $File['BindingFields'];
552 | $preserve = $File['Preserve'];
553 | $searchRows = $File['SearchRows'];
554 | $searchCustom = $File['SearchCustom'];
555 | $formRows = $File['FormRows'];
556 | $formCustom = $File['FormCustom'];
557 | $vwGridColumns = $File['VWGridColumns'];
558 | $vwGridButtons = $File['VWGridButtons'];
559 | $vwFieldsList = $File['VWFieldsList'];
560 | $vwFieldCustom = $File['VWFieldCustom'];
561 | $customButtons = $File['CustomButtons'];
562 | $customBundles = $File['CustomBundles'];
563 | $customFunctions = $File['CustomFunctions'];
564 | $getbyMethods = $File['GetByMethods'];
565 |
566 | // Revisar si se debe preservar el archivo, y si este existe
567 | //
568 | if ($preserve) {
569 | if (file_exists($destination)) {
570 | return;
571 | }
572 | }
573 |
574 | $vwTable = ( substr($Table->Table, 0, 4) == 'Tipo' ) ? $Table->Table : 'VW' . $Table->Table;
575 |
576 | // Obtener el contenido de la plantilla
577 | //
578 | $content = file_get_contents($template);
579 |
580 | // Reemplazar la metadata
581 | //
582 | // NAMESPACE
583 | $content = str_replace('<>', $this->entityNamespace, $content);
584 | $content = str_replace('<>', $this->entityDomain, $content);
585 | $content = str_replace('<>', $Table->Table, $content);
586 | $content = str_replace('<>', $vwTable, $content);
587 | $content = str_replace('<>', $fields[0], $content);
588 | $content = str_replace('<>', $fields[1], $content);
589 |
590 | $content = str_replace('<>', $vwGridColumns, $content);
591 | $content = str_replace('<>', $vwGridButtons, $content);
592 | $content = str_replace('<>', $vwFieldsList, $content);
593 | $content = str_replace('<>', $vwFieldCustom, $content);
594 |
595 | $content = str_replace('<>', $getbyMethods, $content);
596 |
597 | $content = str_replace('<>', $jsonDataFields, $content);
598 | $content = str_replace('<>', $dtoFields, $content);
599 | $content = str_replace('<