PHPCap Docs | PHPCap API
Overview

Namespaces

  • IU
    • PHPCap
  • PHP

Classes

  • IU\PHPCap\ErrorHandler
  • IU\PHPCap\FileUtil
  • IU\PHPCap\RedCap
  • IU\PHPCap\RedCapApiConnection
  • IU\PHPCap\RedCapProject

Interfaces

  • IU\PHPCap\ErrorHandlerInterface
  • IU\PHPCap\RedCapApiConnectionInterface

Exceptions

  • Exception
  • IU\PHPCap\PhpCapException
  • Overview
  • Namespace
  • Class
   1:    2:    3:    4:    5:    6:    7:    8:    9:   10:   11:   12:   13:   14:   15:   16:   17:   18:   19:   20:   21:   22:   23:   24:   25:   26:   27:   28:   29:   30:   31:   32:   33:   34:   35:   36:   37:   38:   39:   40:   41:   42:   43:   44:   45:   46:   47:   48:   49:   50:   51:   52:   53:   54:   55:   56:   57:   58:   59:   60:   61:   62:   63:   64:   65:   66:   67:   68:   69:   70:   71:   72:   73:   74:   75:   76:   77:   78:   79:   80:   81:   82:   83:   84:   85:   86:   87:   88:   89:   90:   91:   92:   93:   94:   95:   96:   97:   98:   99:  100:  101:  102:  103:  104:  105:  106:  107:  108:  109:  110:  111:  112:  113:  114:  115:  116:  117:  118:  119:  120:  121:  122:  123:  124:  125:  126:  127:  128:  129:  130:  131:  132:  133:  134:  135:  136:  137:  138:  139:  140:  141:  142:  143:  144:  145:  146:  147:  148:  149:  150:  151:  152:  153:  154:  155:  156:  157:  158:  159:  160:  161:  162:  163:  164:  165:  166:  167:  168:  169:  170:  171:  172:  173:  174:  175:  176:  177:  178:  179:  180:  181:  182:  183:  184:  185:  186:  187:  188:  189:  190:  191:  192:  193:  194:  195:  196:  197:  198:  199:  200:  201:  202:  203:  204:  205:  206:  207:  208:  209:  210:  211:  212:  213:  214:  215:  216:  217:  218:  219:  220:  221:  222:  223:  224:  225:  226:  227:  228:  229:  230:  231:  232:  233:  234:  235:  236:  237:  238:  239:  240:  241:  242:  243:  244:  245:  246:  247:  248:  249:  250:  251:  252:  253:  254:  255:  256:  257:  258:  259:  260:  261:  262:  263:  264:  265:  266:  267:  268:  269:  270:  271:  272:  273:  274:  275:  276:  277:  278:  279:  280:  281:  282:  283:  284:  285:  286:  287:  288:  289:  290:  291:  292:  293:  294:  295:  296:  297:  298:  299:  300:  301:  302:  303:  304:  305:  306:  307:  308:  309:  310:  311:  312:  313:  314:  315:  316:  317:  318:  319:  320:  321:  322:  323:  324:  325:  326:  327:  328:  329:  330:  331:  332:  333:  334:  335:  336:  337:  338:  339:  340:  341:  342:  343:  344:  345:  346:  347:  348:  349:  350:  351:  352:  353:  354:  355:  356:  357:  358:  359:  360:  361:  362:  363:  364:  365:  366:  367:  368:  369:  370:  371:  372:  373:  374:  375:  376:  377:  378:  379:  380:  381:  382:  383:  384:  385:  386:  387:  388:  389:  390:  391:  392:  393:  394:  395:  396:  397:  398:  399:  400:  401:  402:  403:  404:  405:  406:  407:  408:  409:  410:  411:  412:  413:  414:  415:  416:  417:  418:  419:  420:  421:  422:  423:  424:  425:  426:  427:  428:  429:  430:  431:  432:  433:  434:  435:  436:  437:  438:  439:  440:  441:  442:  443:  444:  445:  446:  447:  448:  449:  450:  451:  452:  453:  454:  455:  456:  457:  458:  459:  460:  461:  462:  463:  464:  465:  466:  467:  468:  469:  470:  471:  472:  473:  474:  475:  476:  477:  478:  479:  480:  481:  482:  483:  484:  485:  486:  487:  488:  489:  490:  491:  492:  493:  494:  495:  496:  497:  498:  499:  500:  501:  502:  503:  504:  505:  506:  507:  508:  509:  510:  511:  512:  513:  514:  515:  516:  517:  518:  519:  520:  521:  522:  523:  524:  525:  526:  527:  528:  529:  530:  531:  532:  533:  534:  535:  536:  537:  538:  539:  540:  541:  542:  543:  544:  545:  546:  547:  548:  549:  550:  551:  552:  553:  554:  555:  556:  557:  558:  559:  560:  561:  562:  563:  564:  565:  566:  567:  568:  569:  570:  571:  572:  573:  574:  575:  576:  577:  578:  579:  580:  581:  582:  583:  584:  585:  586:  587:  588:  589:  590:  591:  592:  593:  594:  595:  596:  597:  598:  599:  600:  601:  602:  603:  604:  605:  606:  607:  608:  609:  610:  611:  612:  613:  614:  615:  616:  617:  618:  619:  620:  621:  622:  623:  624:  625:  626:  627:  628:  629:  630:  631:  632:  633:  634:  635:  636:  637:  638:  639:  640:  641:  642:  643:  644:  645:  646:  647:  648:  649:  650:  651:  652:  653:  654:  655:  656:  657:  658:  659:  660:  661:  662:  663:  664:  665:  666:  667:  668:  669:  670:  671:  672:  673:  674:  675:  676:  677:  678:  679:  680:  681:  682:  683:  684:  685:  686:  687:  688:  689:  690:  691:  692:  693:  694:  695:  696:  697:  698:  699:  700:  701:  702:  703:  704:  705:  706:  707:  708:  709:  710:  711:  712:  713:  714:  715:  716:  717:  718:  719:  720:  721:  722:  723:  724:  725:  726:  727:  728:  729:  730:  731:  732:  733:  734:  735:  736:  737:  738:  739:  740:  741:  742:  743:  744:  745:  746:  747:  748:  749:  750:  751:  752:  753:  754:  755:  756:  757:  758:  759:  760:  761:  762:  763:  764:  765:  766:  767:  768:  769:  770:  771:  772:  773:  774:  775:  776:  777:  778:  779:  780:  781:  782:  783:  784:  785:  786:  787:  788:  789:  790:  791:  792:  793:  794:  795:  796:  797:  798:  799:  800:  801:  802:  803:  804:  805:  806:  807:  808:  809:  810:  811:  812:  813:  814:  815:  816:  817:  818:  819:  820:  821:  822:  823:  824:  825:  826:  827:  828:  829:  830:  831:  832:  833:  834:  835:  836:  837:  838:  839:  840:  841:  842:  843:  844:  845:  846:  847:  848:  849:  850:  851:  852:  853:  854:  855:  856:  857:  858:  859:  860:  861:  862:  863:  864:  865:  866:  867:  868:  869:  870:  871:  872:  873:  874:  875:  876:  877:  878:  879:  880:  881:  882:  883:  884:  885:  886:  887:  888:  889:  890:  891:  892:  893:  894:  895:  896:  897:  898:  899:  900:  901:  902:  903:  904:  905:  906:  907:  908:  909:  910:  911:  912:  913:  914:  915:  916:  917:  918:  919:  920:  921:  922:  923:  924:  925:  926:  927:  928:  929:  930:  931:  932:  933:  934:  935:  936:  937:  938:  939:  940:  941:  942:  943:  944:  945:  946:  947:  948:  949:  950:  951:  952:  953:  954:  955:  956:  957:  958:  959:  960:  961:  962:  963:  964:  965:  966:  967:  968:  969:  970:  971:  972:  973:  974:  975:  976:  977:  978:  979:  980:  981:  982:  983:  984:  985:  986:  987:  988:  989:  990:  991:  992:  993:  994:  995:  996:  997:  998:  999: 1000: 1001: 1002: 1003: 1004: 1005: 1006: 1007: 1008: 1009: 1010: 1011: 1012: 1013: 1014: 1015: 1016: 1017: 1018: 1019: 1020: 1021: 1022: 1023: 1024: 1025: 1026: 1027: 1028: 1029: 1030: 1031: 1032: 1033: 1034: 1035: 1036: 1037: 1038: 1039: 1040: 1041: 1042: 1043: 1044: 1045: 1046: 1047: 1048: 1049: 1050: 1051: 1052: 1053: 1054: 1055: 1056: 1057: 1058: 1059: 1060: 1061: 1062: 1063: 1064: 1065: 1066: 1067: 1068: 1069: 1070: 1071: 1072: 1073: 1074: 1075: 1076: 1077: 1078: 1079: 1080: 1081: 1082: 1083: 1084: 1085: 1086: 1087: 1088: 1089: 1090: 1091: 1092: 1093: 1094: 1095: 1096: 1097: 1098: 1099: 1100: 1101: 1102: 1103: 1104: 1105: 1106: 1107: 1108: 1109: 1110: 1111: 1112: 1113: 1114: 1115: 1116: 1117: 1118: 1119: 1120: 1121: 1122: 1123: 1124: 1125: 1126: 1127: 1128: 1129: 1130: 1131: 1132: 1133: 1134: 1135: 1136: 1137: 1138: 1139: 1140: 1141: 1142: 1143: 1144: 1145: 1146: 1147: 1148: 1149: 1150: 1151: 1152: 1153: 1154: 1155: 1156: 1157: 1158: 1159: 1160: 1161: 1162: 1163: 1164: 1165: 1166: 1167: 1168: 1169: 1170: 1171: 1172: 1173: 1174: 1175: 1176: 1177: 1178: 1179: 1180: 1181: 1182: 1183: 1184: 1185: 1186: 1187: 1188: 1189: 1190: 1191: 1192: 1193: 1194: 1195: 1196: 1197: 1198: 1199: 1200: 1201: 1202: 1203: 1204: 1205: 1206: 1207: 1208: 1209: 1210: 1211: 1212: 1213: 1214: 1215: 1216: 1217: 1218: 1219: 1220: 1221: 1222: 1223: 1224: 1225: 1226: 1227: 1228: 1229: 1230: 1231: 1232: 1233: 1234: 1235: 1236: 1237: 1238: 1239: 1240: 1241: 1242: 1243: 1244: 1245: 1246: 1247: 1248: 1249: 1250: 1251: 1252: 1253: 1254: 1255: 1256: 1257: 1258: 1259: 1260: 1261: 1262: 1263: 1264: 1265: 1266: 1267: 1268: 1269: 1270: 1271: 1272: 1273: 1274: 1275: 1276: 1277: 1278: 1279: 1280: 1281: 1282: 1283: 1284: 1285: 1286: 1287: 1288: 1289: 1290: 1291: 1292: 1293: 1294: 1295: 1296: 1297: 1298: 1299: 1300: 1301: 1302: 1303: 1304: 1305: 1306: 1307: 1308: 1309: 1310: 1311: 1312: 1313: 1314: 1315: 1316: 1317: 1318: 1319: 1320: 1321: 1322: 1323: 1324: 1325: 1326: 1327: 1328: 1329: 1330: 1331: 1332: 1333: 1334: 1335: 1336: 1337: 1338: 1339: 1340: 1341: 1342: 1343: 1344: 1345: 1346: 1347: 1348: 1349: 1350: 1351: 1352: 1353: 1354: 1355: 1356: 1357: 1358: 1359: 1360: 1361: 1362: 1363: 1364: 1365: 1366: 1367: 1368: 1369: 1370: 1371: 1372: 1373: 1374: 1375: 1376: 1377: 1378: 1379: 1380: 1381: 1382: 1383: 1384: 1385: 1386: 1387: 1388: 1389: 1390: 1391: 1392: 1393: 1394: 1395: 1396: 1397: 1398: 1399: 1400: 1401: 1402: 1403: 1404: 1405: 1406: 1407: 1408: 1409: 1410: 1411: 1412: 1413: 1414: 1415: 1416: 1417: 1418: 1419: 1420: 1421: 1422: 1423: 1424: 1425: 1426: 1427: 1428: 1429: 1430: 1431: 1432: 1433: 1434: 1435: 1436: 1437: 1438: 1439: 1440: 1441: 1442: 1443: 1444: 1445: 1446: 1447: 1448: 1449: 1450: 1451: 1452: 1453: 1454: 1455: 1456: 1457: 1458: 1459: 1460: 1461: 1462: 1463: 1464: 1465: 1466: 1467: 1468: 1469: 1470: 1471: 1472: 1473: 1474: 1475: 1476: 1477: 1478: 1479: 1480: 1481: 1482: 1483: 1484: 1485: 1486: 1487: 1488: 1489: 1490: 1491: 1492: 1493: 1494: 1495: 1496: 1497: 1498: 1499: 1500: 1501: 1502: 1503: 1504: 1505: 1506: 1507: 1508: 1509: 1510: 1511: 1512: 1513: 1514: 1515: 1516: 1517: 1518: 1519: 1520: 1521: 1522: 1523: 1524: 1525: 1526: 1527: 1528: 1529: 1530: 1531: 1532: 1533: 1534: 1535: 1536: 1537: 1538: 1539: 1540: 1541: 1542: 1543: 1544: 1545: 1546: 1547: 1548: 1549: 1550: 1551: 1552: 1553: 1554: 1555: 1556: 1557: 1558: 1559: 1560: 1561: 1562: 1563: 1564: 1565: 1566: 1567: 1568: 1569: 1570: 1571: 1572: 1573: 1574: 1575: 1576: 1577: 1578: 1579: 1580: 1581: 1582: 1583: 1584: 1585: 1586: 1587: 1588: 1589: 1590: 1591: 1592: 1593: 1594: 1595: 1596: 1597: 1598: 1599: 1600: 1601: 1602: 1603: 1604: 1605: 1606: 1607: 1608: 1609: 1610: 1611: 1612: 1613: 1614: 1615: 1616: 1617: 1618: 1619: 1620: 1621: 1622: 1623: 1624: 1625: 1626: 1627: 1628: 1629: 1630: 1631: 1632: 1633: 1634: 1635: 1636: 1637: 1638: 1639: 1640: 1641: 1642: 1643: 1644: 1645: 1646: 1647: 1648: 1649: 1650: 1651: 1652: 1653: 1654: 1655: 1656: 1657: 1658: 1659: 1660: 1661: 1662: 1663: 1664: 1665: 1666: 1667: 1668: 1669: 1670: 1671: 1672: 1673: 1674: 1675: 1676: 1677: 1678: 1679: 1680: 1681: 1682: 1683: 1684: 1685: 1686: 1687: 1688: 1689: 1690: 1691: 1692: 1693: 1694: 1695: 1696: 1697: 1698: 1699: 1700: 1701: 1702: 1703: 1704: 1705: 1706: 1707: 1708: 1709: 1710: 1711: 1712: 1713: 1714: 1715: 1716: 1717: 1718: 1719: 1720: 1721: 1722: 1723: 1724: 1725: 1726: 1727: 1728: 1729: 1730: 1731: 1732: 1733: 1734: 1735: 1736: 1737: 1738: 1739: 1740: 1741: 1742: 1743: 1744: 1745: 1746: 1747: 1748: 1749: 1750: 1751: 1752: 1753: 1754: 1755: 1756: 1757: 1758: 1759: 1760: 1761: 1762: 1763: 1764: 1765: 1766: 1767: 1768: 1769: 1770: 1771: 1772: 1773: 1774: 1775: 1776: 1777: 1778: 1779: 1780: 1781: 1782: 1783: 1784: 1785: 1786: 1787: 1788: 1789: 1790: 1791: 1792: 1793: 1794: 1795: 1796: 1797: 1798: 1799: 1800: 1801: 1802: 1803: 1804: 1805: 1806: 1807: 1808: 1809: 1810: 1811: 1812: 1813: 1814: 1815: 1816: 1817: 1818: 1819: 1820: 1821: 1822: 1823: 1824: 1825: 1826: 1827: 1828: 1829: 1830: 1831: 1832: 1833: 1834: 1835: 1836: 1837: 1838: 1839: 1840: 1841: 1842: 1843: 1844: 1845: 1846: 1847: 1848: 1849: 1850: 1851: 1852: 1853: 1854: 1855: 1856: 1857: 1858: 1859: 1860: 1861: 1862: 1863: 1864: 1865: 1866: 1867: 1868: 1869: 1870: 1871: 1872: 1873: 1874: 1875: 1876: 1877: 1878: 1879: 1880: 1881: 1882: 1883: 1884: 1885: 1886: 1887: 1888: 1889: 1890: 1891: 1892: 1893: 1894: 1895: 1896: 1897: 1898: 1899: 1900: 1901: 1902: 1903: 1904: 1905: 1906: 1907: 1908: 1909: 1910: 1911: 1912: 1913: 1914: 1915: 1916: 1917: 1918: 1919: 1920: 1921: 1922: 1923: 1924: 1925: 1926: 1927: 1928: 1929: 1930: 1931: 1932: 1933: 1934: 1935: 1936: 1937: 1938: 1939: 1940: 1941: 1942: 1943: 1944: 1945: 1946: 1947: 1948: 1949: 1950: 1951: 1952: 1953: 1954: 1955: 1956: 1957: 1958: 1959: 1960: 1961: 1962: 1963: 1964: 1965: 1966: 1967: 1968: 1969: 1970: 1971: 1972: 1973: 1974: 1975: 1976: 1977: 1978: 1979: 1980: 1981: 1982: 1983: 1984: 1985: 1986: 1987: 1988: 1989: 1990: 1991: 1992: 1993: 1994: 1995: 1996: 1997: 1998: 1999: 2000: 2001: 2002: 2003: 2004: 2005: 2006: 2007: 2008: 2009: 2010: 2011: 2012: 2013: 2014: 2015: 2016: 2017: 2018: 2019: 2020: 2021: 2022: 2023: 2024: 2025: 2026: 2027: 2028: 2029: 2030: 2031: 2032: 2033: 2034: 2035: 2036: 2037: 2038: 2039: 2040: 2041: 2042: 2043: 2044: 2045: 2046: 2047: 2048: 2049: 2050: 2051: 2052: 2053: 2054: 2055: 2056: 2057: 2058: 2059: 2060: 2061: 2062: 2063: 2064: 2065: 2066: 2067: 2068: 2069: 2070: 2071: 2072: 2073: 2074: 2075: 2076: 2077: 2078: 2079: 2080: 2081: 2082: 2083: 2084: 2085: 2086: 2087: 2088: 2089: 2090: 2091: 2092: 2093: 2094: 2095: 2096: 2097: 2098: 2099: 2100: 2101: 2102: 2103: 2104: 2105: 2106: 2107: 2108: 2109: 2110: 2111: 2112: 2113: 2114: 2115: 2116: 2117: 2118: 2119: 2120: 2121: 2122: 2123: 2124: 2125: 2126: 2127: 2128: 2129: 2130: 2131: 2132: 2133: 2134: 2135: 2136: 2137: 2138: 2139: 2140: 2141: 2142: 2143: 2144: 2145: 2146: 2147: 2148: 2149: 2150: 2151: 2152: 2153: 2154: 2155: 2156: 2157: 2158: 2159: 2160: 2161: 2162: 2163: 2164: 2165: 2166: 2167: 2168: 2169: 2170: 2171: 2172: 2173: 2174: 2175: 2176: 2177: 2178: 2179: 2180: 2181: 2182: 2183: 2184: 2185: 2186: 2187: 2188: 2189: 2190: 2191: 2192: 2193: 2194: 2195: 2196: 2197: 2198: 2199: 2200: 2201: 2202: 2203: 2204: 2205: 2206: 2207: 2208: 2209: 2210: 2211: 2212: 2213: 2214: 2215: 2216: 2217: 2218: 2219: 2220: 2221: 2222: 2223: 2224: 2225: 2226: 2227: 2228: 2229: 2230: 2231: 2232: 2233: 2234: 2235: 2236: 2237: 2238: 2239: 2240: 2241: 2242: 2243: 2244: 2245: 2246: 2247: 2248: 2249: 2250: 2251: 2252: 2253: 2254: 2255: 2256: 2257: 2258: 2259: 2260: 2261: 2262: 2263: 2264: 2265: 2266: 2267: 2268: 2269: 2270: 2271: 2272: 2273: 2274: 2275: 2276: 2277: 2278: 2279: 2280: 2281: 2282: 2283: 2284: 2285: 2286: 2287: 2288: 2289: 2290: 2291: 2292: 2293: 2294: 2295: 2296: 2297: 2298: 2299: 2300: 2301: 2302: 2303: 2304: 2305: 2306: 2307: 2308: 2309: 2310: 2311: 2312: 2313: 2314: 2315: 2316: 2317: 2318: 2319: 2320: 2321: 2322: 2323: 2324: 2325: 2326: 2327: 2328: 2329: 2330: 2331: 2332: 2333: 2334: 2335: 2336: 2337: 2338: 2339: 2340: 2341: 2342: 2343: 2344: 2345: 2346: 2347: 2348: 2349: 2350: 2351: 2352: 2353: 2354: 2355: 2356: 2357: 2358: 2359: 2360: 2361: 2362: 2363: 2364: 2365: 2366: 2367: 2368: 2369: 2370: 2371: 2372: 2373: 2374: 2375: 2376: 2377: 2378: 2379: 2380: 2381: 2382: 2383: 2384: 2385: 2386: 2387: 2388: 2389: 2390: 2391: 2392: 2393: 2394: 2395: 2396: 2397: 2398: 2399: 2400: 2401: 2402: 2403: 2404: 2405: 2406: 2407: 2408: 2409: 2410: 2411: 2412: 2413: 2414: 2415: 2416: 2417: 2418: 2419: 2420: 2421: 2422: 2423: 2424: 2425: 2426: 2427: 2428: 2429: 2430: 2431: 2432: 2433: 2434: 2435: 2436: 2437: 2438: 2439: 2440: 2441: 2442: 2443: 2444: 2445: 2446: 2447: 2448: 2449: 2450: 2451: 2452: 2453: 2454: 2455: 2456: 2457: 2458: 2459: 2460: 2461: 2462: 2463: 2464: 2465: 2466: 2467: 2468: 2469: 2470: 2471: 2472: 2473: 2474: 2475: 2476: 2477: 2478: 2479: 2480: 2481: 2482: 2483: 2484: 2485: 2486: 2487: 2488: 2489: 2490: 2491: 2492: 2493: 2494: 2495: 2496: 2497: 2498: 2499: 2500: 2501: 2502: 2503: 2504: 2505: 2506: 2507: 2508: 2509: 2510: 2511: 2512: 2513: 2514: 2515: 2516: 2517: 2518: 2519: 2520: 2521: 2522: 2523: 2524: 2525: 2526: 2527: 2528: 2529: 2530: 2531: 2532: 2533: 2534: 2535: 2536: 2537: 2538: 2539: 2540: 2541: 2542: 2543: 2544: 2545: 2546: 2547: 2548: 2549: 2550: 2551: 2552: 2553: 2554: 2555: 2556: 2557: 2558: 2559: 2560: 2561: 2562: 2563: 2564: 2565: 2566: 2567: 2568: 2569: 2570: 2571: 2572: 2573: 2574: 2575: 2576: 2577: 2578: 2579: 2580: 2581: 2582: 2583: 2584: 2585: 2586: 2587: 2588: 2589: 2590: 2591: 2592: 2593: 2594: 2595: 2596: 2597: 2598: 2599: 2600: 2601: 2602: 2603: 2604: 2605: 2606: 2607: 2608: 2609: 2610: 2611: 2612: 2613: 2614: 2615: 2616: 2617: 2618: 2619: 2620: 2621: 2622: 2623: 2624: 2625: 2626: 2627: 2628: 2629: 2630: 2631: 2632: 2633: 2634: 2635: 2636: 2637: 2638: 2639: 2640: 2641: 2642: 2643: 2644: 2645: 2646: 2647: 2648: 2649: 2650: 2651: 2652: 2653: 2654: 2655: 2656: 2657: 2658: 2659: 2660: 2661: 2662: 2663: 2664: 2665: 2666: 2667: 2668: 2669: 2670: 2671: 2672: 2673: 2674: 2675: 2676: 2677: 2678: 2679: 2680: 2681: 2682: 2683: 2684: 2685: 2686: 2687: 2688: 
<?php
/**
 * This file contains the REDCap project class for PHPCap.
 */
namespace IU\PHPCap;

/**
 * REDCap project class used to retrieve data from, and modify, REDCap projects.
 */
class RedCapProject
{
    const JSON_RESULT_ERROR_PATTERN = '/^[\s]*{"error":[\s]*"(.*)"}[\s]*$/';
    
    /** string REDCap API token for the project */
    protected $apiToken;
    
    /** RedCapApiConnection connection to the REDCap API at the $apiURL. */
    protected $connection;
    
    /** Error handler for the project. */
    protected $errorHandler;
 
    
    /**
     * Creates a REDCapProject object for the specifed project.
     *
     * Example Usage:
     * <code>
     * $apiUrl = 'https://redcap.someplace.edu/api/'; # replace with your API URL
     * $apiToken = '11111111112222222222333333333344'; # replace with your API token
     * $sslVerify = true;
     *
     * # See the PHPCap documentation for information on how to set this file up
     * $caCertificateFile = 'USERTrustRSACertificationAuthority.crt';
     *
     * $project = new RedCapProject($apiUrl, $apiToken, $sslVerify, $caCertificateFile);
     * </code>
     *
     * @param string $apiUrl the URL for the API for the REDCap site that has the project.
     * @param string $apiToken the API token for this project.
     * @param boolean $sslVerify indicates if SSL connection to REDCap web site should be verified.
     * @param string $caCertificateFile the full path name of the CA (Certificate Authority)
     *     certificate file.
     * @param ErrorHandlerInterface $errorHandler the error handler used by the project.
     *    This would normally only be set if you want to override the PHPCap's default
     *    error handler.
     * @param RedCapApiConnectionInterface $connection the connection used by the project.
     *    This would normally only be set if you want to override the PHPCap's default
     *    connection. If this argument is specified, the $apiUrl, $sslVerify, and
     *    $caCertificateFile arguments will be ignored, and the values for these
     *    set in the connection will be used.
     * @throws PhpCapException if any of the arguments are invalid
     */
    public function __construct(
        $apiUrl,
        $apiToken,
        $sslVerify = false,
        $caCertificateFile = null,
        $errorHandler = null,
        $connection = null
    ) {
        # Need to set errorHandler to default to start in case there is an
        # error with the errorHandler passed as an argument
        # (to be able to handle that error!)
        $this->errorHandler = new ErrorHandler();
        if (isset($errorHandler)) {
            $this->errorHandler = $this->processErrorHandlerArgument($errorHandler);
        }
        
        $this->apiToken = $this->processApiTokenArgument($apiToken);
        
        if (isset($connection)) {
            $this->connection = $this->processConnectionArgument($connection);
        } else {
            $this->apiUrl      = $this->processApiUrlArgument($apiUrl);
            $sslVerify         = $this->processSslVerifyArgument($sslVerify);
            $caCertificateFile = $this->processCaCertificateFileArgument($caCertificateFile);
            
            $this->connection = new RedCapApiConnection($apiUrl, $sslVerify, $caCertificateFile);
        }
    }

    
    /**
     * Exports the numbers and names of the arms in the project.
     *
     * @param $format string the format used to export the arm data.
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     * @param array $arms array of integers or numeric strings that are the numbers of the arms to export.
     *     If no arms are specified, then information for all arms will be returned.
     *
     * @return mixed For 'php' format, array of arrays that have the following keys:
     *     <ul>
     *       <li>'arm_num'</li>
     *       <li>'name'</li>
     *     </ul>
     */
    public function exportArms($format = 'php', $arms = [])
    {
        $data = array(
                'token' => $this->apiToken,
                'content' => 'arm',
                'returnFormat' => 'json'
        );
        
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        $data['arms']   = $this->processArmsArgument($arms);
        
        $arms = $this->connection->callWithArray($data);
        $arms = $this->processExportResult($arms, $format);
        
        return $arms;
    }
    
    /**
     * Imports the specified arms into the project.
     *
     * @param mixed $arms the arms to import. This will
     *     be a PHP array of associative arrays if no format, or 'php' format was specified,
     *     and a string otherwise. The field names (keys) used in both cases
     *     are: arm_num, name
     * @param string $format the format for the export.
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     * @param boolean $override
     *     <ul>
     *       <li> false - [default] don't delete existing arms; only add new
     *       arms or renames existing arms.
     *       </li>
     *       <li> true - delete all existing arms before importing.</li>
     *     </ul>
     * @throws PhpCapException if an error occurs.
     *
     * @return integer the number of arms imported.
     */
    public function importArms($arms, $format = 'php', $override = false)
    {
        $data = array(
                'token'        => $this->apiToken,
                'content'      => 'arm',
                'action'       => 'import',
                'returnFormat' => 'json'
        );
        
        #---------------------------------------
        # Process arguments
        #---------------------------------------
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format']   = $this->processFormatArgument($format, $legalFormats);
        $data['data']     = $this->processImportDataArgument($arms, 'arms', $format);
        $data['override'] = $this->processOverrideArgument($override);
        
        $result = $this->connection->callWithArray($data);
        
        $this->processNonExportResult($result);
        
        return (integer) $result;
    }
    
    /**
     * Deletes the specified arms from the project.
     *
     * @param array $arms array of arm numbers to delete.
     *
     * @throws PhpCapException if an error occurs, including if the arms array is null or empty
     *
     * @return integer the number of arms deleted.
     */
    public function deleteArms($arms)
    {
        $data = array (
                'token'        => $this->apiToken,
                'content'      => 'arm',
                'action'       => 'delete',
                'returnFormat' => 'json',
        );
        
        $data['arms'] = $this->processArmsArgument($arms, $required = true);
       
        $result = $this->connection->callWithArray($data);
        
        $this->processNonExportResult($result);
        
        return (integer) $result;
    }


    /**
     * Exports information about the specified events.
     *
     * Example usage:
     * <code>
     * #export information about all events in CSV (Comma-Separated Values) format.
     * $eventInfo = $project->exportEvents('csv');
     *
     * # export events in XML format for arms 1 and 2.
     * $eventInfo = $project->exportEvents('xml', [1, 2]);
     * </code>
     *
     * @param string $format the format for the export.
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     * @param array $arms array of integers or numeric strings that are the arm numbers for
     *     which events should be exported.
     *     If no arms are specified, then all events will be returned.
     *
     * @return array information about the specified events. Each element of the
     *     array is an associative array with the following keys: 'event_name', 'arm_num',
     *         'day_offset', 'offset_min', 'offset_max', 'unique_event_name', 'custom_event_label'
     */
    public function exportEvents($format = 'php', $arms = [])
    {
        $data = array(
                'token' => $this->apiToken,
                'content' => 'event',
                'returnFormat' => 'json'
        );
        
        #---------------------------------------
        # Process arguments
        #---------------------------------------
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        $data['arms'] = $this->processArmsArgument($arms);
        
        
        #------------------------------------------------------
        # Get and process events
        #------------------------------------------------------
        $events = $this->connection->callWithArray($data);
        $events = $this->processExportResult($events, $format);
        
        return $events;
    }
    
    
    /**
     * Imports the specified events into the project.
     *
     * @param mixed $events the events to import. This will
     *     be a PHP array of associative arrays if no format, or 'php' format is specified,
     *     and a string otherwise. The field names (keys) used in both cases
     *     are: event_name, arm_num
     * @param string $format the format for the export.
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     * @param boolean $override
     *     <ul>
     *       <li> false - [default] don't delete existing arms; only add new
     *       arms or renames existing arms.
     *       </li>
     *       <li> true - delete all existing arms before importing.</li>
     *     </ul>
     *
     * @throws PhpCapException if an error occurs.
     *
     * @return integer the number of events imported.
     */
    public function importEvents($events, $format = 'php', $override = false)
    {
        $data = array(
                'token'        => $this->apiToken,
                'content'      => 'event',
                'action'       => 'import',
                'returnFormat' => 'json'
        );
        
        #---------------------------------------
        # Process arguments
        #---------------------------------------
        $data['data'] = $this->processImportDataArgument($events, 'arms', $format);
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        $data['override'] = $this->processOverrideArgument($override);
        
        $result = $this->connection->callWithArray($data);
        
        $this->processNonExportResult($result);
        
        return (integer) $result;
    }

    
    /**
     * Deletes the specified events from the project.
     *
     * @param array $events array of event names of events to delete.
     *
     * @throws PhpCapException if an error occurs, including if the events array is null or empty.
     *
     * @return integer the number of events deleted.
     */
    public function deleteEvents($events)
    {
        $data = array (
                'token'        => $this->apiToken,
                'content'      => 'event',
                'action'       => 'delete',
                'returnFormat' => 'json',
        );
        
        $data['events'] = $this->processEventsArgument($events, $required = true);
        
        $result = $this->connection->callWithArray($data);
        
        $this->processNonExportResult($result);
        
        return (integer) $result;
    }
    
    
    /**
     * Exports the fields names for a project.
     *
     * @param string $format the format for the export.
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     * @param string $field the name of the field for which to export field
     *     name information. If no field is specified, information for all
     *     fields is exported.
     *
     * @return mixed information on the field specified, or all fields if no
     *     field was specified. If 'php' or no format was specified, results
     *     will be returned as a PHP array of maps (associative arrays), where the
     *     keys for the maps:
     *     <ul>
     *       <li>original_field_name</li>
     *       <li>choice_value</li>
     *       <li>export_field_name</li>
     *     </ul>
     */
    public function exportFieldNames($format = 'php', $field = null)
    {
        $data = array(
                'token' => $this->apiToken,
                'content' => 'exportFieldNames',
                'returnFormat' => 'json'
        );
        
        #---------------------------------------
        # Process arguments
        #---------------------------------------
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        $data['field']  = $this->processFieldArgument($field, $required = false);
        
        $fieldNames = $this->connection->callWithArray($data);
        $fieldNames = $this->processExportResult($fieldNames, $format);
        
        return $fieldNames;
    }

    /**
     * Exports the specified file.
     *
     * @param string $recordId the record ID for the file to be exported.
     * @param string $field the name of the field containing the file to export.
     * @param string $event name of event for file export (for longitudinal studies).
     * @param integer $repeatInstance
     *
     * @throws PhpCapException if an error occurs.
     *
     * @return string the contents of the file that was exported.
     */
    public function exportFile($recordId, $field, $event = null, $repeatInstance = null)
    {
        $data = array(
                'token'        => $this->apiToken,
                'content'      => 'file',
                'action'       => 'export',
                'returnFormat' => 'json'
        );
        
        #--------------------------------------------
        # Process arguments
        #--------------------------------------------
        $data['record']           = $this->processRecordIdArgument($recordId);
        $data['field']            = $this->processFieldArgument($field);
        $data['event']            = $this->processEventArgument($event);
        $data['repeat_instance']  = $this->processRepeatInstanceArgument($repeatInstance);
        
        #-------------------------------
        # Get and process file
        #-------------------------------
        $file = $this->connection->callWithArray($data);
        $file = $this->processExportResult($file, $format = 'file');
        
        return $file;
    }
    
    
    /**
     * Imports the file into the field of the record
     * with the specified event and/or repeat istance, if any.
     *
     * Example usage:
     * <code>
     * ...
     * $file     = '../data/consent1001.txt';
     * $recordId = '1001';
     * $field    = 'patient_document';
     * $event    = 'enrollment_arm_1';
     * $project->importFile($file, $recordId, $field, $event);
     * ...
     * </code>
     *
     * @param string $filename the name of the file to import.
     * @param string $recordId the record ID of the record to import the file into.
     * @param string $field the field of the record to import the file into.
     * @param string $event the event of the record to import the file into
     *     (only for longitudinal studies).
     * @param integer $repeatInstance the repeat instance of the record to import
     *     the file into (only for studies that have repeating events
     *     and/or instruments).
     *
     * @throws PhpCapException
     */
    public function importFile($filename, $recordId, $field, $event = null, $repeatInstance = null)
    {
        $data = array (
                'token'        => $this->apiToken,
                'content'      => 'file',
                'action'       => 'import',
                'returnFormat' => 'json'
        );
        
        #----------------------------------------
        # Process non-file arguments
        #----------------------------------------
        $data['file']             = $this->processFilenameArgument($filename);
        $data['record']           = $this->processRecordIdArgument($recordId);
        $data['field']            = $this->processFieldArgument($field);
        $data['event']            = $this->processEventArgument($event);
        $data['repeat_instance']  = $this->processRepeatInstanceArgument($repeatInstance);
        
        
        #---------------------------------------------------------------------
        # For unknown reasons, "call" (instead of "callWithArray") needs to
        # be used here (probably something to do with the 'file' data).
        # REDCap's "API Playground" (also) makes no data conversion for this
        # method.
        #---------------------------------------------------------------------
        $result = $this->connection->call($data);
        
        $this->processNonExportResult($result);
    }


    /**
     * Deletes the specified file.
     *
     * @param string $recordId the record ID of the file to delete.
     * @param string $field the field name of the file to delete.
     * @param string $event the event of the file to delete
     *     (only for longitudinal studies).
     * @param integer $repeatInstance repeat instance of the file to delete
     *     (only for studies that have repeating events
     *     and/or instruments).
     */
    public function deleteFile($recordId, $field, $event = null, $repeatInstance = null)
    {
        $data = array (
                'token'        => $this->apiToken,
                'content'      => 'file',
                'action'       => 'delete',
                'returnFormat' => 'json'
        );
        
        #----------------------------------------
        # Process arguments
        #----------------------------------------
        $data['record']           = $this->processRecordIdArgument($recordId);
        $data['field']            = $this->processFieldArgument($field);
        $data['event']            = $this->processEventArgument($event);
        $data['repeat_instance']  = $this->processRepeatInstanceArgument($repeatInstance);
        
        $result = $this->connection->callWithArray($data);
        
        $this->processNonExportResult($result);
        
        return $result;
    }
    
    
    /**
     * Exports information about the instruments (data entry forms) for the project.
     *
     * Example usage:
     * <code>
     * $instruments = $project->getInstruments();
     * foreach ($instruments as $instrumentName => $instrumentLabel) {
     *     print "{$instrumentName} : {$instrumentLabel}\n";
     * }
     * </code>
     *
     * @param $format string format instruments are exported in:
     *     <ul>
     *       <li>'php' - [default] returns data as a PHP array</li>
     *       <li>'csv' - string of CSV (comma-separated values)</li>
     *       <li>'json' - string of JSON encoded data</li>
     *       <li>'xml' - string of XML encoded data</li>
     *     </ul>
     *
     * @return mixed For the 'php' format, and array map of instrument names to instrument labels is returned.
     *     For all other formats a string is returned.
     */
    public function exportInstruments($format = 'php')
    {
        $data = array(
                'token'       => $this->apiToken,
                'content'     => 'instrument',
                'returnFormat' => 'json'
        );
        
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        
        $instrumentsData = $this->connection->callWithArray($data);
        
        $instrumentsData = $this->processExportResult($instrumentsData, $format);
        
        #------------------------------------------------------
        # If format is 'php', reformat the data as
        # a map from "instrument name" to "instrument label"
        #------------------------------------------------------
        if ($format == 'php') {
            $instruments = array ();
            foreach ($instrumentsData as $instr) {
                $instruments [$instr ['instrument_name']] = $instr ['instrument_label'];
            }
        } else {
            $instruments = $instrumentsData;
        }
        
        return $instruments;
    }
    
    /**
     * Exports a PDF version of the requested instruments (forms).
     *
     * @param string $file the name of the file (possibly with a path specified also)
     *     to store the PDF instruments in.
     * @param string $recordId if record ID is specified, the forms retrieved will
     *     be filled with values for that record. Otherwise, they will be blank.
     * @param string $event (only for longitudinal projects) a unique event name
     *     that is used when a record ID has been specified to return only
     *     forms that are in that event (for the specified records).
     * @param string $form if this is specified, only this form will be
     *     returned.
     * @param boolean $allRecords if this is set to true, all forms for all
     *     records will be retrieved (the $recordId, $event, and $form arguments
     *     will be ignored).
     *
     * @throws PhpCapException if an error occurs.
     *
     * @return string PDF content of requested instruments (forms).
     */
    public function exportPdfFileOfInstruments(
        $file = null,
        $recordId = null,
        $event = null,
        $form = null,
        $allRecords = null
    ) {
        $data = array(
                'token'       => $this->apiToken,
                'content'     => 'pdf',
                'returnFormat' => 'json'
        );
        
        $file = $this->processFileArgument($file);
        
        $data['record']     = $this->processRecordIdArgument($recordId, $required = false);
        $data['event']      = $this->processEventArgument($event);
        $data['instrument'] = $this->processFormArgument($form);
        $data['allRecords'] = $this->processAllRecordsArgument($allRecords);
        
        $result = $this->connection->callWithArray($data);
        
        if (isset($file)) {
            FileUtil::writeStringToFile($result, $file);
        }
        
        return $result;
    }
   
    
    /**
     * Gets the instrument to event mapping for the project.
     *
     * For example, the following code:
     * <code>
     * $map = $project->exportInstrumentEventMappings();
     * print_r($map[0]); # print first element of map
     * </code>
     * might generate the following output:
     * <pre>
     * Array
     * (
     *     [arm_num] => 1
     *     [unique_event_name] => enrollment_arm_1
     *     [form] => demographics
     * )
     * </pre>
     *
     * @param string $format the format in which to export the records:
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     * @param array $arms array of integers or numeric strings that are the numbers of the arms
     *     for which instrument/event mapping infomation should be exported.
     *     If no arms are specified, then information for all arms will be exported.
     *
     * @return arrray an array of arrays that have the following keys:
     *     <ul>
     *       <li>'arm_num'</li>
     *       <li>'unique_event_name'</li>
     *       <li>'form'</li>
     *     </ul>
     */
    public function exportInstrumentEventMappings($format = 'php', $arms = [])
    {
        $data = array(
                'token'        => $this->apiToken,
                'content'      => 'formEventMapping',
                'format'       => 'json',
                'returnFormat' => 'json'
        );
        
        #------------------------------------------
        # Process arguments
        #------------------------------------------
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        $data['arms']   = $this->processArmsArgument($arms);
        
        #---------------------------------------------
        # Get and process instrument-event mappings
        #---------------------------------------------
        $instrumentEventMappings = $this->connection->callWithArray($data);
        $instrumentEventMappings = $this->processExportResult($instrumentEventMappings, $format);
        
        return $instrumentEventMappings;
    }

    /**
     * Imports the specified instrument-event mappings into the project.
     *
     * @param mixed $mappings the mappings to import. This will
     *     be a PHP array of associative arrays if no format, or
     *     'php' format, was specified,
     *     and a string otherwise. In all cases, the field names that
     *     are used in the mappings are:
     *     arm_num, unique_event_name, form
     * @param string $format the format for the export.
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     *
     * @throws PhpCapException if an error occurs.
     *
     * @return integer the number of mappings imported.
     */
    public function importInstrumentEventMappings($mappings, $format = 'php')
    {
        $data = array(
            'token'        => $this->apiToken,
            'content'      => 'formEventMapping',
            'returnFormat' => 'json'
        );
        
        #---------------------------------------
        # Process arguments
        #---------------------------------------
        $data['data'] = $this->processImportDataArgument($mappings, 'mappings', $format);
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        
        $result = $this->connection->callWithArray($data);
        
        $this->processNonExportResult($result);
        
        return (integer) $result;
    }
    
    
    /**
     * Exports metadata about the project, i.e., information about the fields in the project.
     *
     * @param string $format the format for the export.
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     * @param array $fields array of field names for which metadata should be exported
     * @param array $forms array of form names. Metadata will be exported for all fields in the
     *     specified forms.
     *
     * @return array associative array (map) of metatdata for the project, which consists of
     *         information about each field. Some examples of the information
     *         provided are: 'field_name', 'form_name', 'field_type', 'field_label'.
     *         See REDCap API documentation
     *         for more information, or use the print_r function on the results of this method.
     */
    public function exportMetadata($format = 'php', $fields = [], $forms = [])
    {
        $data = array(
                'token' => $this->apiToken,
                'content' => 'metadata',
                'returnFormat' => 'json'
        );
        
        #---------------------------------------
        # Process format
        #---------------------------------------
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        $data['forms']  = $this->processFormsArgument($forms);
        $data['fields'] = $this->processFieldsArgument($fields);
        
        #-------------------------------------------
        # Get and process metadata
        #-------------------------------------------
        $metadata = $this->connection->callWithArray($data);
        $metadata = $this->processExportResult($metadata, $format);
        
        return $metadata;
    }
    
    /**
     * Imports the specified metadata (field information) into the project.
     *
     * @param mixed $metadata the metadata to import. This will
     *     be a PHP associative array if no format, or 'php' format was specified,
     *     and a string otherwise.
     * @param string $format the format for the export.
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     *
     * @throws PhpCapException if an error occurs.
     *
     * @return integer the number of fields imported.
     */
    public function importMetadata($metadata, $format = 'php')
    {
        $data = array(
                'token'        => $this->apiToken,
                'content'      => 'metadata',
                'returnFormat' => 'json'
        );
        
        #---------------------------------------
        # Process arguments
        #---------------------------------------
        $data['data'] = $this->processImportDataArgument($metadata, 'metadata', $format);
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        
        $result = $this->connection->callWithArray($data);
        
        $this->processNonExportResult($result);
        
        return (integer) $result;
    }

    
    /**
     * Exports information about the project, e.g., project ID, project title, creation time.
     *
     * @param string $format the format for the export.
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     *
     * @return array associative array (map) of project information. See REDCap API documentation
     *         for a list of the fields, or use the print_r function on the results of this method.
     */
    public function exportProjectInfo($format = 'php')
    {
        $data = array(
                'token'        => $this->apiToken,
                'content'      => 'project',
                'returnFormat' => 'json'
        );
        
        #---------------------------------------
        # Process format
        #---------------------------------------
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        
        #---------------------------------------
        # Get and process project information
        #---------------------------------------
        $projectInfo = $this->connection->callWithArray($data);
        $projectInfo = $this->processExportResult($projectInfo, $format);
        
        return $projectInfo;
    }
    
    /**
     * Imports the specified project information into the project.
     * The valid fields that can be imported are:
     *
     * project_title, project_language, purpose, purpose_other, project_notes,
     * custom_record_label, secondary_unique_field, is_longitudinal,
     * surveys_enabled, scheduling_enabled, record_autonumbering_enabled,
     * randomization_enabled, project_irb_number, project_grant_number,
     * project_pi_firstname, project_pi_lastname, display_today_now_button
     *
     * You do not need to specify all of these fields when doing an import,
     * only the ones that you actually want to change. For example:
     * <code>
     * ...
     * # Set the project to be longitudinal and enable surveys
     * $projectInfo = ['is_longitudinal' => 1, 'surveys_enabled' => 1];
     * $project->importProjectInfo($projectInfo);
     * ...
     * </code>
     *
     * @param mixed $projectInfo the project information to import. This will
     *     be a PHP associative array if no format, or 'php' format was specified,
     *     and a string otherwise.
     * @param string $format the format for the export.
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     *
     * @throws PhpCapException if an error occurs.
     *
     * @return integer the number of project info values specified that were valid,
     *     whether or not each valid value actually caused an update (i.e., was different
     *     from the existing value before the method call).
     */
    public function importProjectInfo($projectInfo, $format = 'php')
    {
        $data = array(
            'token'        => $this->apiToken,
            'content'      => 'project_settings',
            'returnFormat' => 'json'
        );
        
        #---------------------------------------
        # Process arguments
        #---------------------------------------
        $data['data'] = $this->processImportDataArgument($projectInfo, 'projectInfo', $format);
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        
        $result = $this->connection->callWithArray($data);
        
        $this->processNonExportResult($result);
        
        return (integer) $result;
    }
    
    /**
     * Exports the specified information of project in XML format.
     *
     * @param boolean $returnMetadataOnly if this is set to true, only the metadata for
     *     the project is returned. If it is not set to true, the metadata and data for the project
     *     is returned.
     * @param array $recordIds array of strings with record id's that are to be retrieved.
     * @param array $fields array of field names to export
     * @param array $events array of event names for which fields should be exported
     * @param array $filterLogic logic used to restrict the records retrieved, e.g.,
     *     "[last_name] = 'Smith'".
     * @param boolean $exportSurveyFields specifies whether survey fields should be exported.
     *     <ul>
     *       <li> true - export the following survey fields:
     *         <ul>
     *           <li> survey identifier field ('redcap_survey_identifier') </li>
     *           <li> survey timestamp fields (instrument+'_timestamp') </li>
     *         </ul>
     *       </li>
     *       <li> false - [default] survey fields are not exported.</li>
     *     </ul>
     * @param boolean $exportDataAccessGroups specifies whether the data access group field
     *      ('redcap_data_access_group') should be exported.
     *     <ul>
     *       <li> true - export the data access group field if there is at least one data access group, and
     *                   the user calling the method (as identified by the API token) is not
     *                   in a data access group.</li>
     *       <li> false - [default] don't export the data access group field.</li>
     *     </ul>
     * @param boolean $exportFiles If this is set to true, files will be exported in the XML.
     *     If it is not set to true, files will not be exported.
     * @return string the specified information for the project in XML format.
     */
    public function exportProjectXml(
        $returnMetadataOnly = false,
        $recordIds = null,
        $fields = null,
        $events = null,
        $filterLogic = null,
        $exportSurveyFields = false,
        $exportDataAccessGroups = false,
        $exportFiles = false
    ) {
        $data = array(
                'token'        => $this->apiToken,
                'content'      => 'project_xml',
                'returnFormat' => 'json'
        );
        
        #---------------------------------------------
        # Process the arguments
        #---------------------------------------------
        $data['returnMetadataOnly'] = $this->processReturnMetadataOnlyArgument($returnMetadataOnly);

        $data['records']     = $this->processRecordIdsArgument($recordIds);
        $data['fields']      = $this->processFieldsArgument($fields);
        $data['events']      = $this->processEventsArgument($events);
        $data['filterLogic'] = $this->processFilterLogicArgument($filterLogic);
        
        $data['exportSurveyFields']     = $this->processExportSurveyFieldsArgument($exportSurveyFields);
        $data['exportDataAccessGroups'] = $this->processExportDataAccessGroupsArgument($exportDataAccessGroups);
        $data['exportFiles']            = $this->processExportFilesArgument($exportFiles);
        
        #---------------------------------------
        # Get the Project XML and process it
        #---------------------------------------
        $projectXml = $this->connection->callWithArray($data);
        $projectXml = $this->processExportResult($projectXml, $format = 'xml');
        
        return $projectXml;
    }
    
    /**
     * This method returns the next potential record ID for a project, but it does NOT
     * actually create a new record. The record ID returned will generally be the current maximum
     * record ID number incremented by one (but see the REDCap documentation for the case
     * where Data Access Groups are being used).
     * This method is intended for use with projects that have record-autonumbering enabled.
     *
     * @return string the next record name.
     */
    public function generateNextRecordName()
    {
        $data = array(
                'token'        => $this->apiToken,
                'content'      => 'generateNextRecordName',
                'returnFormat' => 'json'
        );
        
        $nextRecordName = $this->connection->callWithArray($data);
        $nextRecordName = $this->processExportResult($nextRecordName, $format = 'number');
        
        return $nextRecordName;
    }
    
    
    /**
     * Exports the specified records.
     *
     * Example usage:
     * <code>
     * $records = $project->exportRecords($format = 'csv', $type = 'flat');
     * $recordIds = [1001, 1002, 1003];
     * $records = $project->exportRecords('xml', 'eav', $recordIds);
     * </code>
     *
     * @param string $format the format in which to export the records:
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *       <li> 'odm' - string with CDISC ODM XML format, specifically ODM version 1.3.1</li>
     *     </ul>
     * @param string $type the type of records exported:
     *     <ul>
     *       <li>'flat' - [default] exports one record per row.</li>
     *       <li>'eav'  - exports one data point per row:, so,
     *         for non-longitudinal studies, each record will have the following
     *         fields: record_id, field_name, value. For longitudinal studies, each record
     *         will have the fields: record_id, field_name, value, redcap_event_name.
     *       </li>
     *     </ul>
     * @param array $recordIds array of strings with record id's that are to be retrieved.
     * @param array $fields array of field names to export
     * @param array $forms array of form names for which fields should be exported
     * @param array $events array of event names for which fields should be exported
     * @param array $filterLogic logic used to restrict the records retrieved, e.g.,
     *         "[last_name] = 'Smith'".
     * @param string $rawOrLabel indicates what should be exported for options of multiple choice fields:
     *     <ul>
     *       <li> 'raw' - [default] export the raw coded values</li>
     *       <li> 'label' - export the labels</li>
     *     </ul>
     * @param string $rawOrLabelHeaders when exporting with 'csv' format 'flat' type, indicates what format
     *         should be used for the CSV headers:
     *         <ul>
     *           <li> 'raw' - [default] export the variable/field names</li>
     *           <li> 'label' - export the field labels</li>
     *         </ul>
     * @param boolean $exportCheckboxLabel specifies the format for checkbox fields for the case where
     *         $format = 'csv', $rawOrLabel = true, and $type = 'flat'. For other cases this
     *         parameter is effectively ignored.
     *     <ul>
     *       <li> true - checked checkboxes will have a value equal to the checkbox option's label
     *           (e.g., 'Choice 1'), and unchecked checkboxes will have a blank value.
     *       </li>
     *       <li> false - [default] checked checkboxes will have a value of 'Checked', and
     *            unchecked checkboxes will have a value of 'Unchecked'.
     *       </li>
     *     </ul>
     * @param boolean $exportSurveyFields specifies whether survey fields should be exported.
     *     <ul>
     *       <li> true - export the following survey fields:
     *         <ul>
     *           <li> survey identifier field ('redcap_survey_identifier') </li>
     *           <li> survey timestamp fields (instrument+'_timestamp') </li>
     *         </ul>
     *       </li>
     *       <li> false - [default] survey fields are not exported.</li>
     *     </ul>
     * @param boolean $exportDataAccessGroups specifies whether the data access group field
     *      ('redcap_data_access_group') should be exported.
     *     <ul>
     *       <li> true - export the data access group field if there is at least one data access group, and
     *                   the user calling the method (as identified by the API token) is not
     *                   in a data access group.</li>
     *       <li> false - [default] don't export the data access group field.</li>
     *     </ul>
     *
     * @return mixed If 'php' format is specified, an array of records will be returned where the format
     *     of the records depends on the 'type'parameter (see above). For other
     *     formats, a string is returned that contains the records in the specified format.
     */
    public function exportRecords(
        $format = 'php',
        $type = 'flat',
        $recordIds = null,
        $fields = null,
        $forms = null,
        $events = null,
        $filterLogic = null,
        $rawOrLabel = 'raw',
        $rawOrLabelHeaders = 'raw',
        $exportCheckboxLabel = false,
        $exportSurveyFields = false,
        $exportDataAccessGroups = false
    ) {
        $data = array(
                'token'        => $this->apiToken,
                'content'      => 'record',
                'returnFormat' => 'json'
        );
        
        #---------------------------------------
        # Process the arguments
        #---------------------------------------
        $legalFormats = array('php', 'csv', 'json', 'xml', 'odm');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        
        $data['type']    = $this->processTypeArgument($type);
        $data['records'] = $this->processRecordIdsArgument($recordIds);
        $data['fields']  = $this->processFieldsArgument($fields);
        $data['forms']   = $this->processFormsArgument($forms);
        $data['events']  = $this->processEventsArgument($events);
        
        $data['rawOrLabel']             = $this->processRawOrLabelArgument($rawOrLabel);
        $data['rawOrLabelHeaders']      = $this->processRawOrLabelHeadersArgument($rawOrLabelHeaders);
        $data['exportCheckboxLabel']    = $this->processExportCheckboxLabelArgument($exportCheckboxLabel);
        $data['exportSurveyFields']     = $this->processExportSurveyFieldsArgument($exportSurveyFields);
        $data['exportDataAccessGroups'] = $this->processExportDataAccessGroupsArgument($exportDataAccessGroups);
        
        $data['filterLogic'] = $this->processFilterLogicArgument($filterLogic);
        
        #---------------------------------------
        # Get the records and process them
        #---------------------------------------
        $records = $this->connection->callWithArray($data);
        $records = $this->processExportResult($records, $format);
      
        return $records;
    }

    /**
     * Export records using an array parameter, where the keys of the array
     * passed to this method are the argument names, and the values are the
     * argument values. The argument names to use correspond to the variable
     * names in the exportRecords method.
     *
     * Example usage:
     *
     * <code>
     * # return all records with last name "Smith" in CSV format
     * $records = $project->exportRecordsAp(['format' => 'csv', 'filterLogic' => "[last_name] = 'Smith'"]);
     *
     * # export only records that have record ID 1001, 1002, or 1003
     * $result = $project->exportRecordsAp(['recordIds' => [1001, 1002, 1003]]);
     *
     * # export only the fields on the 'lab_data' form and field 'study_id'
     * $records = $project->exportRecordsAp(['forms' => ['lab_data'], 'fields' => ['study_id']]);
     * </code>
     *
     * @see exportRecords()
     *
     * @param array $argumentArray array of arguments.
     * @return mixed the specified records.
     */
    public function exportRecordsAp($arrayParameter = [])
    {
        if (func_num_args() > 1) {
            $message = __METHOD__.'() was called with '.func_num_args().' arguments, but '
                    .' it accepts at most 1 argument.';
            $this->errorHandler->throwException($message, ErrorHandlerInterface::TOO_MANY_ARGUMENTS);
        } elseif (!isset($arrayParameter)) {
            $arrayParameter = [];
        } elseif (!is_array($arrayParameter)) {
            $message = 'The argument has type "'
                    .gettype($arrayParameter)
                    .'", but it needs to be an array.';
            $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT);
        } // @codeCoverageIgnore
        
        $num = 1;
        foreach ($arrayParameter as $name => $value) {
            if (gettype($name) !== 'string') {
                $message = 'Argument name number '.$num.' in the array argument has type '
                        .gettype($name).', but it needs to be a string.';
                $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT);
            } // @codeCoverageIgnore
            
            switch ($name) {
                case 'format':
                    $format = $value;
                    break;
                case 'type':
                    $type = $value;
                    break;
                case 'recordIds':
                    $recordIds = $value;
                    break;
                case 'fields':
                    $fields = $value;
                    break;
                case 'forms':
                    $forms = $value;
                    break;
                case 'events':
                    $events = $value;
                    break;
                case 'filterLogic':
                    $filterLogic = $value;
                    break;
                case 'rawOrLabel':
                    $rawOrLabel = $value;
                    break;
                case 'rawOrLabelHeaders':
                    $rawOrLabelHeaders = $value;
                    break;
                case 'exportCheckboxLabel':
                    $exportCheckboxLabel = $value;
                    break;
                case 'exportSurveyFields':
                    $exportSurveyFields = $value;
                    break;
                case 'exportDataAccessGroups':
                    $exportDataAccessGroups = $value;
                    break;
                default:
                    $this->errorHandler->throwException(
                        'Unrecognized argument name "' . $name . '".',
                        ErrorHandlerInterface::INVALID_ARGUMENT
                    );
                    break; // @codeCoverageIgnore
            }
            $num++;
        }
        
        $records = $this->exportRecords(
            isset($format)                 ? $format                 : 'php',
            isset($type)                   ? $type                   : 'flat',
            isset($recordIds)              ? $recordIds              : null,
            isset($fields)                 ? $fields                 : null,
            isset($forms)                  ? $forms                  : null,
            isset($events)                 ? $events                 : null,
            isset($filterLogic)            ? $filterLogic            : null,
            isset($rawOrLabel)             ? $rawOrLabel             : 'raw',
            isset($rawOrLabelHeaders)      ? $rawOrLabelHeaders      : 'raw',
            isset($exportCheckboxLabel)    ? $exportCheckboxLabel    : false,
            isset($exportSurveyFields)     ? $exportSurveyFields     : false,
            isset($exportDataAccessGroups) ? $exportDataAccessGroups : false
        );
        
        return $records;
    }

    
    /**
     * Imports the specified records into the project.
     *
     * @param mixed $records
     *            If the 'php' (default) format is being used, an array of associated arrays (maps)
     *            where each key is a field name,
     *            and its value is the value to store in that field. If any other format is being used, then
     *            the records are represented by a string.
     * @param string $format One of the following formats can be specified
     *            <ul>
     *              <li> 'php' - [default] array of maps of values</li>
     *              <li> 'csv' - string of CSV (comma-separated values)</li>
     *              <li> 'json' - string of JSON encoded values</li>
     *              <li> 'xml' - string of XML encoded data</li>
     *              <li> 'odm' - CDISC ODM XML format, specifically ODM version 1.3.1</li>
     *            </ul>
     * @param string $type
     *            <ul>
     *              <li> 'flat' - [default] each data element is a record</li>
     *              <li> 'eav' - each data element is one value</li>
     *            </ul>
     * @param string $overwriteBehavior
     *            <ul>
     *              <li>normal - [default] blank/empty values will be ignored</li>
     *              <li>overwrite - blank/empty values are valid and will overwrite data</li>
     *            </ul>
     * @param string $dateFormat date format which can be one of the following:
     *            <ul>
     *              <li>'YMD' - [default] Y-M-D format (e.g., 2016-12-31)</li>
     *              <li>'MDY' - M/D/Y format (e.g., 12/31/2016)</li>
     *              <li>'DMY' - D/M/Y format (e.g., 31/12/2016)</li>
     *           </ul>
     * @param string $returnContent specifies what should be returned:
     *           <ul>
     *             <li>'count' - [default] the number of records imported</li>
     *             <li>'ids' - an array of the record IDs imported is returned</li>
     *             <li>'auto_ids' - an array of comma-separated record ID pairs, with
     *                 the new ID created and the corresponding ID that
     *                 was sent, for the records that were imported.
     *                 This can only be used if $forceAutoNumber is set to true.</li>
     *           </ul>
     * @param boolean $forceAutoNumber enables automatic assignment of record IDs of imported
     *         records by REDCap.
     *         If this is set to true, and auto-numbering for records is enabled for the project,
     *         auto-numbering of imported records will be enabled.
     *
     * @return mixed if 'count' was specified for 'returnContent', then an integer will
     *         be returned that is the number of records imported.
     *         If 'ids' was specified, then an array of record IDs that were imported will
     *         be returned. If 'auto_ids' was specified, an array that maps newly created IDs
     *         to sent IDs will be returned.
     */
    public function importRecords(
        $records,
        $format = 'php',
        $type = 'flat',
        $overwriteBehavior = 'normal',
        $dateFormat = 'YMD',
        $returnContent = 'count',
        $forceAutoNumber = false
    ) {
            
        $data = array (
            'token'         => $this->apiToken,
            'content'       => 'record',
            'returnFormat'  => 'json'
        );
            
        #---------------------------------------
        # Process format
        #---------------------------------------
        $legalFormats = array('csv', 'json', 'odm', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        $data['data']   = $this->processImportDataArgument($records, 'records', $format);
        $data['type']   = $this->processTypeArgument($type);
            
        $data['overwriteBehavior'] = $this->processOverwriteBehaviorArgument($overwriteBehavior);
        $data['forceAutoNumber']   = $this->processForceAutoNumberArgument($forceAutoNumber);
        $data['returnContent']     = $this->processReturnContentArgument($returnContent, $forceAutoNumber);
        $data['dateFormat']        = $this->processDateFormatArgument($dateFormat);
        
        $result = $this->connection->callWithArray($data);

        $this->processNonExportResult($result);
        
        
        #--------------------------------------------------------------------------
        # Process result, which should either be a count of the records imported,
        # or a list of the record IDs that were imported
        #
        # The result should be a string in JSON for all formats.
        # Need to convert the result to a PHP data structure.
        #--------------------------------------------------------------------------
        $phpResult = json_decode($result, true); // true => return as array instead of object
        
        $jsonError = json_last_error();
        
        switch ($jsonError) {
            case JSON_ERROR_NONE:
                $result = $phpResult;
                # If this is a count, then just return the count, and not an
                # array that has a count index with the count
                if (isset($result) && is_array($result) && array_key_exists('count', $result)) {
                    $result = $result['count'];
                }
                break;
            default:
                # Hopefully the REDCap API will always return valid JSON, and this
                # will never happen.
                $message =  'JSON error ('.$jsonError.') "'.json_last_error_msg().
                    '" while processing import return value: "'.
                $result.'".';
                $this->errorHandler->throwException($message, ErrorHandlerInterface::JSON_ERROR);
                break; // @codeCoverageIgnore
        }
        
        return $result;
    }
    
    
    /**
     * Deletes the specified records from the project.
     *
     * @param array $recordIds array of record IDs to delete
     * @param string $arm if an arm is specified, only records that have
     *     one of the specified record IDs that are in that arm will
     *     be deleted.
     *
     * @throws PhpCapException
     *
     * @return integer the number of records deleted. Note that as of
     *     REDCap version 7.0.15 (at least) the number of records
     *     deleted will not be correct for the case where an arm
     *     is specified and some of the record IDs specified are
     *     not in that arm.
     */
    public function deleteRecords($recordIds, $arm = null)
    {
        $data = array (
                'token'        => $this->apiToken,
                'content'      => 'record',
                'action'       => 'delete',
                'returnFormat' => 'json',
        );
        
        $data['records'] = $this->processRecordIdsArgument($recordIds);
        $data['arm']     = $this->processArmArgument($arm);
        
        $result = $this->connection->callWithArray($data);
        
        $this->processNonExportResult($result);
        
        return $result;
    }

    
    /**
     * Gets the REDCap version number of the REDCap instance being used by the project.
     *
     * @return string the REDCap version number of the REDCap instance being used by the project.
     */
    public function exportRedcapVersion()
    {
        $data = array(
                'token' => $this->apiToken,
                'content' => 'version'
        );
        
        $redcapVersion = $this->connection->callWithArray($data);
        $recapVersion = $this->processExportResult($redcapVersion, 'string');
        
        return $redcapVersion;
    }
    
    
    
    /**
     * Exports the records produced by the specified report.
     *
     * @param mixed $reportId integer or numeric string ID of the report to use.
     * @param string $format output data format.
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     * @param string $rawOrLabel indicates what should be exported for options of multiple choice fields:
     *     <ul>
     *       <li> 'raw' - [default] export the raw coded values</li>
     *       <li> 'label' - export the labels</li>
     *     </ul>
     * @param string $rawOrLabelHeaders when exporting with 'csv' format 'flat' type, indicates what format
     *         should be used for the CSV headers:
     *         <ul>
     *           <li> 'raw' - [default] export the variable/field names</li>
     *           <li> 'label' - export the field labels</li>
     *         </ul>
     * @param boolean $exportCheckboxLabel specifies the format for checkbox fields for the case where
     *         $format = 'csv', $rawOrLabel = true, and $type = 'flat'. For other cases this
     *         parameter is effectively ignored.
     *     <ul>
     *       <li> true - checked checkboxes will have a value equal to the checkbox option's label
     *           (e.g., 'Choice 1'), and unchecked checkboxes will have a blank value.
     *       </li>
     *       <li> false - [default] checked checkboxes will have a value of 'Checked', and
     *            unchecked checkboxes will have a value of 'Unchecked'.
     *       </li>
     *     </ul>
     *
     * @return mixed the records generated by the specefied report in the specified format.
     */
    public function exportReports(
        $reportId,
        $format = 'php',
        $rawOrLabel = 'raw',
        $rawOrLabelHeaders = 'raw',
        $exportCheckboxLabel = false
    ) {
        $data = array(
                'token' => $this->apiToken,
                'content' => 'report',
                'returnFormat' => 'json'
        );
        
        #------------------------------------------------
        # Process arguments
        #------------------------------------------------
        $data['report_id'] = $this->processReportIdArgument($reportId);

        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);

        $data['rawOrLabel']          = $this->processRawOrLabelArgument($rawOrLabel);
        $data['rawOrLabelHeaders']   = $this->processRawOrLabelHeadersArgument($rawOrLabelHeaders);
        $data['exportCheckboxLabel'] = $this->processExportCheckboxLabelArgument($exportCheckboxLabel);
        
        #---------------------------------------------------
        # Get and process records
        #---------------------------------------------------
        $records = $this->connection->callWithArray($data);
        $records = $this->processExportResult($records, $format);
         
        return $records;
    }

    
    /**
     * Exports the survey link for the specified inputs.
     *
     * @param string $recordId the record ID for the link.
     * @param string $form the form for the link.
     * @param string $event event for link (for longitudinal studies only).
     * @param integer $repeatInstance for repeatable forms, the instance of the form
     *     to return a link for.
     *
     * @return string survey link.
     */
    public function exportSurveyLink($recordId, $form, $event = null, $repeatInstance = null)
    {
        $data = array(
                'token' => $this->apiToken,
                'content' => 'surveyLink',
                'returnFormat' => 'json'
        );
        
        #----------------------------------------------
        # Process arguments
        #----------------------------------------------
        $data['record']          = $this->processRecordIdArgument($recordId, $required = true);
        $data['instrument']      = $this->ProcessFormArgument($form, $required = true);
        $data['event']           = $this->ProcessEventArgument($event);
        $data['repeat_instance'] = $this->ProcessRepeatInstanceArgument($repeatInstance);
        
        $surveyLink = $this->connection->callWithArray($data);
        $surveyLink = $this->processExportResult($surveyLink, 'string');
        
        return $surveyLink;
    }
    
    /**
     * Exports the list of survey participants for the specified form and, for
     * longitudinal studies, event.
     *
     * @param string $form the form for which the participants should be exported.
     * @param string $format output data format.
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     * @param string $event the event name for which survey participants should be
     *     exported.
     *
     * @return mixed for the 'php' format, an array of arrays of participant
     *     information is returned, for all other formats, the data is returned
     *     in the specified format as a string.
     */
    public function exportSurveyParticipants($form, $format = 'php', $event = null)
    {
        $data = array(
                'token' => $this->apiToken,
                'content' => 'participantList',
                'returnFormat' => 'json'
        );
        
        #----------------------------------------------
        # Process arguments
        #----------------------------------------------
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format']     = $this->processFormatArgument($format, $legalFormats);
        $data['instrument'] = $this->ProcessFormArgument($form, $required = true);
        $data['event']      = $this->ProcessEventArgument($event);
        
        $surveyParticipants = $this->connection->callWithArray($data);
        $surveyParticipants = $this->processExportResult($surveyParticipants, $format);
        
        return $surveyParticipants;
    }
    
    /**
     * Exports the survey queue link for the specified record ID.
     *
     * @param string $recordId the record ID of the survey queue link that should be returned.
     *
     * @return string survey queue link.
     */
    public function exportSurveyQueueLink($recordId)
    {
        $data = array(
                'token' => $this->apiToken,
                'content' => 'surveyQueueLink',
                'returnFormat' => 'json'
        );
        
        #----------------------------------------------
        # Process arguments
        #----------------------------------------------
        $data['record'] = $this->processRecordIdArgument($recordId, $required = true);
        
        $surveyQueueLink = $this->connection->callWithArray($data);
        $surveyQueueLink = $this->processExportResult($surveyQueueLink, 'string');
        
        return $surveyQueueLink;
    }
    
    /**
     * Exports the code for returning to a survey that was not completed.
     *
     * @param string $recordId the record ID for the survey to return to.
     * @param string $form the form name of the survey to return to.
     * @param string $event the unique event name (for longitudinal studies) for the survey
     *     to return to.
     * @param integer $repeatInstance the repeat instance (if any) for the survey to return to.
     * @return string survey return code.
     */
    public function exportSurveyReturnCode($recordId, $form, $event = null, $repeatInstance = null)
    {
        $data = array(
                'token' => $this->apiToken,
                'content' => 'surveyReturnCode',
                'returnFormat' => 'json'
        );
        
        #----------------------------------------------
        # Process arguments
        #----------------------------------------------
        $data['record']          = $this->processRecordIdArgument($recordId, $required = true);
        $data['instrument']      = $this->ProcessFormArgument($form, $required = true);
        $data['event']           = $this->ProcessEventArgument($event);
        $data['repeat_instance'] = $this->ProcessRepeatInstanceArgument($repeatInstance);
        
        $surveyReturnCode = $this->connection->callWithArray($data);
        $surveyReturnCode = $this->processExportResult($surveyReturnCode, 'string');
        
        return $surveyReturnCode;
    }
    
    
    /**
     * Exports the users of the project.
     *
     * @param string $format output data format.
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     *
     * @return mixed a list of users. For the 'php' format an array of associative
     *     arrays is returned, where the keys are the field names and the values
     *     are the field values. For all other formats, a string is returned with
     *     the data in the specified format.
     */
    public function exportUsers($format = 'php')
    {
        $data = array(
                'token' => $this->apiToken,
                'content' => 'user',
                'returnFormat' => 'json'
        );
        
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        
        #---------------------------------------------------
        # Get and process users
        #---------------------------------------------------
        $users = $this->connection->callWithArray($data);
        $users = $this->processExportResult($users, $format);
        
        return $users;
    }
    
    /**
     * Imports the specified users into the project. This method
     * can also be used to update user priveleges by importing
     * a users that already exist in the project and
     * specifying new privleges for that user in the user
     * data that is imported.
     *
     * The available field names for user import are:
     * <code>
     * username, expiration, data_access_group, design,
     * user_rights, data_access_groups, data_export, reports, stats_and_charts,
     * manage_survey_participants, calendar, data_import_tool, data_comparison_tool,
     * logging, file_repository, data_quality_create, data_quality_execute,
     * api_export, api_import, mobile_app, mobile_app_download_data,
     * record_create, record_rename, record_delete,
     * lock_records_customization, lock_records, lock_records_all_forms,
     * forms
     * </code>
     *
     *
     * Privileges for fields above can be set as follows:
     * <ul>
     *   <li><b>Data Export:</b> 0=No Access, 2=De-Identified, 1=Full Data Set</li>
     *   <li><b>Form Rights:</b> 0=No Access, 2=Read Only,
     *       1=View records/responses and edit records (survey responses are read-only),
     *       3=Edit survey responses</li>
     *   <li><b>Other field values:</b> 0=No Access, 1=Access.</li>
     * </ul>
     *
     * See the REDCap API documentation for more information, or print the results
     * of PHPCap's exportUsers method to see what the data looks like for the current users.
     *
     * @param mixed $users for 'php' format, an array should be used that
     *     maps field names to field values. For all other formats a string
     *     should be used that has the data in the correct format.
     * @param string $format output data format.
     *     <ul>
     *       <li> 'php' - [default] array of maps of values</li>
     *       <li> 'csv' - string of CSV (comma-separated values)</li>
     *       <li> 'json' - string of JSON encoded values</li>
     *       <li> 'xml' - string of XML encoded data</li>
     *     </ul>
     *
     * @return integer the number of users added or updated.
     */
    public function importUsers($users, $format = 'php')
    {
        $data = array(
            'token' => $this->apiToken,
            'content' => 'user',
            'returnFormat' => 'json'
        );
        
        #----------------------------------------------------
        # Process arguments
        #----------------------------------------------------
        $legalFormats = array('csv', 'json', 'php', 'xml');
        $data['format'] = $this->processFormatArgument($format, $legalFormats);
        $data['data']   = $this->processImportDataArgument($users, 'users', $format);
        
        #---------------------------------------------------
        # Get and process users
        #---------------------------------------------------
        $result = $this->connection->callWithArray($data);
        $this->processNonExportResult($result);
        
        return (integer) $result;
    }
    
 
    /**
     * Gets an array of record ID batches.
     *
     * These can be used for batch
     * processing of records exports to lessen memory requirements, for example:
     * <code>
     * ...
     * # Get all the record IDs of the project in 10 batches
     * $recordIdBatches = $project->getRecordIdBatches(10);
     * foreach ($recordIdBatches as $recordIdBatch) {
     *     $records = $project->exportRecordsAp(['recordIds' => $recordIdBatch]);
     *     ...
     * }
     * ...
     * </code>
     *
     * @param integer $batchSize the batch size in number of record IDs.
     *     The last batch may have less record IDs. For example, if you had 500
     *     record IDs and specified a batch size of 200, the first 2 batches would have
     *     200 record IDs, and the last batch would have 100.
     * @param array $filterLogic logic used to restrict the records retrieved, e.g.,
     *     "[last_name] = 'Smith'". This could be used for batch processing a subset
     *     of the records.
     * @param $recordIdFieldName the name of the record ID field. Specifying this is not
     *     necessary, but will speed things up, because it will eliminate the need for
     *     this method to call the REDCap API to retrieve the value.
     * @return array an array or record ID arrays, where each record ID array
     *     is considered to be a batch. Each batch can be used as the value
     *     for the records IDs parameter for an export records method.
     */
    public function getRecordIdBatches($batchSize = null, $filterLogic = null, $recordIdFieldName = null)
    {
        $recordIdBatches = array();
        
        #-----------------------------------
        # Check arguments
        #-----------------------------------
        if (!isset($batchSize)) {
            $message = 'The number of batches was not specified.';
            $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT);
        } elseif (!is_int($batchSize)) {
            $message = "The batch size argument has type '".gettype($batchSize).'", '
                .'but it should have type integer.';
                $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT);
        } elseif ($batchSize < 1) {
            $message = 'The batch size argument is less than 1. It needs to be at least 1.';
            $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT);
        } // @codeCoverageIgnore
        
        $filterLogic = $this->processFilterLogicArgument($filterLogic);
        
        if (!isset($recordIdFieldName)) {
            $recordIdFieldName = $this->getRecordIdFieldName();
        }
        
        $records = $this->exportRecordsAp(
            ['fields' => [$recordIdFieldName], 'filterLogic' => $filterLogic]
        );
        $recordIds = array_column($records, $recordIdFieldName);
        $recordIds = array_unique($recordIds);  # Remove duplicate record IDs
        
        $numberOfRecordIds = count($recordIds);
        
        $position = 0;
        for ($position = 0; $position < $numberOfRecordIds; $position += $batchSize) {
            $recordIdBatch = array();
            $recordIdBatch = array_slice($recordIds, $position, $batchSize);
            array_push($recordIdBatches, $recordIdBatch);
        }
        
        return $recordIdBatches;
    }
    
    
    
    /**
     * Gets the record ID field name for the project.
     *
     * @return string the field name of the record ID field of the project.
     */
    public function getRecordIdFieldName()
    {
        $metadata = $this->exportMetaData();
        $recordIdFieldName = $metadata[0]['field_name'];
        return $recordIdFieldName;
    }

    /**
     * Gets the API token for the project.
     *
     * @return string the API token for the project.
     */
    public function getApiToken()
    {
        return $this->apiToken;
    }
    
    
    /**
     * Returns the underlying REDCap API connection being used by the project.
     * This can be used to make calls to the REDCap API, possibly to access functionality
     * not supported by PHPCap.
     *
     * @return RedCapApiConnectionInterface the underlying REDCap API connection being
     *         used by the project.
     */
    public function getConnection()
    {
        return $this->connection;
    }
    
    /**
     * Sets the connection used for calling the REDCap API.
     *
     * @param RedCapApiConnectionInterface $connection the connection to use
     *     for calls to the REDCap API.
     */
    public function setConnection($connection)
    {
        $this->connection = $this->processConnectionArgument($connection);
    }
    
    /**
     * Gets the error handler.
     *
     * @return ErrorHandlerInterface the error handler being used.
     */
    public function getErrorHandler()
    {
        return $this->errorHandler;
    }
    
    /**
     * Sets the error handler used by the project.
     *
     * @param ErrorHandlerInterface $errorHandler the error handler to use.
     */
    public function setErrorHandler($errorHandler)
    {
        $this->errorHandler = $this->processErrorHandlerArgument($errorHandler);
    }


    protected function processAllRecordsArgument($allRecords)
    {
        if (!isset($allRecords)) {
            ;  // That's OK
        } elseif (!is_bool($allRecords)) {
            $message = 'The allRecords argument has type "'.gettype($allRecords).
            '", but it should be a boolean (true/false).';
            $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT);
        } elseif ($allRecords !== true) {
            $allRecords = null; // need to reset to null, because ANY (non-null) value
                                // will cause the REDCap API to return all records
        }
        
        return $allRecords;
    }

    protected function processApiTokenArgument($apiToken)
    {
        if (!isset($apiToken)) {
            $message = 'The REDCap API token specified for the project was null or blank.';
            $code    =  ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } elseif (gettype($apiToken) !== 'string') {
            $message = 'The REDCap API token provided should be a string, but has type: '
                .gettype($apiToken);
            $code =  ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } elseif (!ctype_xdigit($apiToken)) {   // ctype_xdigit - check token for hexidecimal
            $message = 'The REDCap API token has an invalid format.'
                .' It should only contain numbers and the letters A, B, C, D, E and F.';
            $code = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } elseif (strlen($apiToken) != 32) { # Note: super tokens are not valid for project methods
            $message = 'The REDCap API token has an invalid format.'
                .' It has a length of '.strlen($apiToken).' characters, but should have a length of'
                .' 32.';
            $code = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        return $apiToken;
    }
    
    protected function processApiUrlArgument($apiUrl)
    {
        # Note: standard PHP URL validation will fail for non-ASCII URLs (so it was not used)
        if (!isset($apiUrl)) {
            $message = 'The REDCap API URL specified for the project was null or blank.';
            $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } elseif (gettype($apiUrl) !== 'string') {
            $message = 'The REDCap API URL provided ('.$apiUrl.') should be a string, but has type: '
                . gettype($apiUrl);
            $code = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        return $apiUrl;
    }
    
    
    protected function processArmArgument($arm)
    {
        if (!isset($arm)) {
            ;  // That's OK
        } elseif (is_string($arm)) {
            if (! preg_match('/^[0-9]+$/', $arm)) {
                $this->errorHandler->throwException(
                    'Arm number "' . $arm . '" is non-numeric string.',
                    ErrorHandlerInterface::INVALID_ARGUMENT
                );
            } // @codeCoverageIgnore
        } elseif (is_int($arm)) {
            if ($arm < 0) {
                $this->errorHandler->throwException(
                    'Arm number "' . $arm . '" is a negative integer.',
                    ErrorHandlerInterface::INVALID_ARGUMENT
                );
            } // @codeCoverageIgnore
        } else {
            $message = 'The arm argument has type "'.gettype($arm)
                .'"; it should be an integer or a (numeric) string.';
            $code = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        
        return $arm;
    }
    
    protected function processArmsArgument($arms, $required = false)
    {
        if (!isset($arms)) {
            if ($required === true) {
                $this->errorHandler->throwException(
                    'The arms argument was not set.',
                    ErrorHandlerInterface::INVALID_ARGUMENT
                );
            } // @codeCoverageIgnore
            $arms = array();
        } else {
            if (!is_array($arms)) {
                $this->errorHandler->throwException(
                    'The arms argument has invalid type "'.gettype($arms).'"; it should be an array.',
                    ErrorHandlerInterface::INVALID_ARGUMENT
                );
            } elseif ($required === true && count($arms) < 1) {
                $this->errorHandler->throwException(
                    'No arms were specified in the arms argument; at least one must be specified.',
                    ErrorHandlerInterface::INVALID_ARGUMENT
                );
            } // @codeCoverageIgnore
        }
        
        foreach ($arms as $arm) {
            if (is_string($arm)) {
                if (! preg_match('/^[0-9]+$/', $arm)) {
                    $this->errorHandler->throwException(
                        'Arm number "' . $arm . '" is non-numeric string.',
                        ErrorHandlerInterface::INVALID_ARGUMENT
                    );
                } // @codeCoverageIgnore
            } elseif (is_int($arm)) {
                if ($arm < 0) {
                    $this->errorHandler->throwException(
                        'Arm number "' . $arm . '" is a negative integer.',
                        ErrorHandlerInterface::INVALID_ARGUMENT
                    );
                } // @codeCoverageIgnore
            } else {
                $message = 'An arm was found in the arms array that has type "'.gettype($arm).
                '"; it should be an integer or a (numeric) string.';
                $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT);
            } // @codeCoverageIgnore
        }
        
        return $arms;
    }
    
    protected function processCaCertificateFileArgument($caCertificateFile)
    {
        if (isset($caCertificateFile) && gettype($caCertificateFile) !== 'string') {
            $message = 'The value for $sslVerify must be a string, but has type: '
                .gettype($caCertificateFile);
            $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        return $caCertificateFile;
    }
    
    protected function processConnectionArgument($connection)
    {
        if (!($connection instanceof RedCapApiConnectionInterface)) {
            $message = 'The connection argument is not valid, because it doesn\'t implement '
                .RedCapApiConnectionInterface::class.'.';
            $code = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        return $connection;
    }
    
    protected function processDateFormatArgument($dateFormat)
    {
        if (!isset($dateFormat)) {
            $dateFormat = 'YMD';
        } else {
            if (gettype($dateFormat) === 'string') {
                $dateFormat = strtoupper($dateFormat);
            }
            
            $legalDateFormats = ['MDY', 'DMY', 'YMD'];
            if (!in_array($dateFormat, $legalDateFormats)) {
                $message = 'Invalid date format "'.$dateFormat.'" specified.'
                    .' The date format should be one of the following: "'
                    .implode('", "', $legalDateFormats).'".';
                    $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        }
        
        return $dateFormat;
    }
    
    protected function processErrorHandlerArgument($errorHandler)
    {
        if (!($errorHandler instanceof ErrorHandlerInterface)) {
            $message = 'The error handler argument is not valid, because it doesn\'t implement '
                .ErrorHandlerInterface::class.'.';
            $code = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        return $errorHandler;
    }
    
    protected function processEventArgument($event)
    {
        if (!isset($event)) {
            ; // This might be OK
        } elseif (gettype($event) !== 'string') {
            $message = 'Event has type "'.gettype($event).'", but should be a string.';
            $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT);
        } // @codeCoverageIgnore
        return $event;
    }
    
    protected function processEventsArgument($events, $required = false)
    {
        if (!isset($events)) {
            if ($required === true) {
                $message = 'The events argument was not set.';
                $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
            $events = array();
        } else {
            if (!is_array($events)) {
                $message = 'The events argument has invalid type "'.gettype($events)
                    .'"; it should be an array.';
                $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } elseif ($required === true && count($events) < 1) {
                $message = 'No events were specified in the events argument;'
                    .' at least one must be specified.';
                $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } else { // @codeCoverageIgnore
                foreach ($events as $event) {
                    $type = gettype($event);
                    if (strcmp($type, 'string') !== 0) {
                        $message = 'An event with type "'.$type.'" was found in the events array.'.
                            ' Events should be strings.';
                        $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                        $this->errorHandler->throwException($message, $code);
                    } // @codeCoverageIgnore
                }
            }
        }
        
        return $events;
    }
    
    
    protected function processExportCheckboxLabelArgument($exportCheckboxLabel)
    {
        if ($exportCheckboxLabel == null) {
            $exportCheckboxLabel = false;
        } else {
            if (gettype($exportCheckboxLabel) !== 'boolean') {
                $this->errorHandler->throwException(
                    'Invalid type for exportCheckboxLabel. It should be a boolean (true or false),'
                    .' but has type: '.gettype($exportCheckboxLabel).'.',
                    ErrorHandlerInterface::INVALID_ARGUMENT
                );
            } // @codeCoverageIgnore
        }
        return $exportCheckboxLabel;
    }
    
    protected function processExportDataAccessGroupsArgument($exportDataAccessGroups)
    {
        if ($exportDataAccessGroups == null) {
            $exportDataAccessGroups = false;
        } else {
            if (gettype($exportDataAccessGroups) !== 'boolean') {
                $message = 'Invalid type for exportDataAccessGroups.'
                    .' It should be a boolean (true or false),'
                    .' but has type: '.gettype($exportDataAccessGroups).'.';
                $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        }
        return $exportDataAccessGroups;
    }
    
    protected function processExportFilesArgument($exportFiles)
    {
        if ($exportFiles== null) {
            $exportFiles= false;
        } else {
            if (gettype($exportFiles) !== 'boolean') {
                $message = 'Invalid type for exportFiles. It should be a boolean (true or false),'
                    .' but has type: '.gettype($exportFiles).'.';
                $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        }
        return $exportFiles;
    }
    
    /**
     * Processes an export result from the REDCap API.
     *
     * @param string $result
     * @param string $format
     * @throws PhpCapException
     */
    protected function processExportResult(& $result, $format)
    {
        if ($format == 'php') {
            $phpResult = json_decode($result, true); // true => return as array instead of object
                
            $jsonError = json_last_error();
                
            switch ($jsonError) {
                case JSON_ERROR_NONE:
                    $result = $phpResult;
                    break;
                default:
                    $message =  "JSON error (" . $jsonError . ") \"" . json_last_error_msg()
                        ."\" in REDCap API output."
                        ."\nThe first 1,000 characters of output returned from REDCap are:\n"
                        .substr($result, 0, 1000);
                    $code = ErrorHandlerInterface::JSON_ERROR;
                    $this->errorHandler->throwException($message, $code);
                    break; // @codeCoverageIgnore
            }
                
            if (array_key_exists('error', $result)) {
                $this->errorHandler->throwException($result ['error'], ErrorHandlerInterface::REDCAP_API_ERROR);
            } // @codeCoverageIgnore
        } else {
            // If this is a format other than 'php', look for a JSON error, because
            // all formats return errors as JSON
            $matches = array();
            $hasMatch = preg_match(self::JSON_RESULT_ERROR_PATTERN, $result, $matches);
            if ($hasMatch === 1) {
                // note: $matches[0] is the complete string that matched
                //       $matches[1] is just the error message part
                $message = $matches[1];
                $this->errorHandler->throwException($message, ErrorHandlerInterface::REDCAP_API_ERROR);
            } // @codeCoverageIgnore
        }
        
        return $result;
    }
    
    protected function processExportSurveyFieldsArgument($exportSurveyFields)
    {
        if ($exportSurveyFields == null) {
            $exportSurveyFields = false;
        } else {
            if (gettype($exportSurveyFields) !== 'boolean') {
                $message =  'Invalid type for exportSurveyFields.'
                    .' It should be a boolean (true or false),'
                    .' but has type: '.gettype($exportSurveyFields).'.';
                $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        }
        return $exportSurveyFields;
    }
    
    protected function processFieldArgument($field, $required = true)
    {
        if (!isset($field)) {
            if ($required) {
                $message = 'No field was specified.';
                $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT);
            }  // @codeCoverageIgnore
            // else OK
        } elseif (gettype($field) !== 'string') {
            $message = 'Field has type "'.gettype($field).'", but should be a string.';
            $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT);
        } // @codeCoverageIgnore
        return $field;
    }
    
    
    protected function processFieldsArgument($fields)
    {
        if (!isset($fields)) {
            $fields = array();
        } else {
            if (!is_array($fields)) {
                $message = 'Argument "fields" has the wrong type; it should be an array.';
                $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } else { // @codeCoverageIgnore
                foreach ($fields as $field) {
                    $type = gettype($field);
                    if (strcmp($type, 'string') !== 0) {
                        $message = 'A field with type "'.$type.'" was found in the fields array.'.
                            ' Fields should be strings.';
                        $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                        $this->errorHandler->throwException($message, $code);
                    } // @codeCoverageIgnore
                }
            }
        }
        
        return $fields;
    }

    protected function processFileArgument($file)
    {
        if (isset($file)) {
            if (gettype($file) !== 'string') {
                $message = "Argument 'file' has type '".gettype($file)."', but should be a string.";
                $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        }
        return $file;
    }
    
    protected function processFilenameArgument($filename)
    {
        if (!isset($filename)) {
            $message = 'No filename specified.';
            $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } elseif (gettype($filename) !== 'string') {
            $message = "Argument 'filename' has type '".gettype($filename)."', but should be a string.";
            $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } elseif (!file_exists($filename)) {
            $message = 'The input file "'.$filename.'" could not be found.';
            $code    = ErrorHandlerInterface::INPUT_FILE_NOT_FOUND;
            $this->errorHandler->throwException($message, $code);
        } elseif (!is_readable($filename)) {
            $message = 'The input file "'.$filename.'" was unreadable.';
            $code    = ErrorHandlerInterface::INPUT_FILE_UNREADABLE;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        
        $basename = pathinfo($filename, PATHINFO_BASENAME);
        $curlFile = curl_file_create($filename, 'text/plain', $basename);
        
        return $curlFile;
    }
    
    
    protected function processFilterLogicArgument($filterLogic)
    {
        if ($filterLogic == null) {
            $filterLogic = '';
        } else {
            if (gettype($filterLogic) !== 'string') {
                $message = 'Invalid type for filterLogic. It should be a string, but has type "'
                    .gettype($filterLogic).'".';
                $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        }
        return $filterLogic;
    }
    
    protected function processForceAutoNumberArgument($forceAutoNumber)
    {
        if ($forceAutoNumber == null) {
            $forceAutoNumber = false;
        } else {
            if (gettype($forceAutoNumber) !== 'boolean') {
                $message = 'Invalid type for forceAutoNumber.'
                    .' It should be a boolean (true or false),'
                    .' but has type: '.gettype($forceAutoNumber).'.';
                $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        }
        return $forceAutoNumber;
    }
    
    protected function processFormArgument($form, $required = false)
    {
        if (!isset($form)) {
            if ($required === true) {
                $message = 'The form argument was not set.';
                $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
            $form = '';
        } elseif (!is_string($form)) {
            $message = 'The form argument has invalid type "'.gettype($form)
                .'"; it should be a string.';
            $code = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        
        return $form;
    }
    
    protected function processFormatArgument(& $format, $legalFormats)
    {
        if (!isset($format)) {
            $format = 'php';
        }
        
        if (gettype($format) !== 'string') {
            $message = 'The format specified has type "'.gettype($format)
                .'", but it should be a string.';
            $code = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        
        $format = strtolower(trim($format));
        
        if (!in_array($format, $legalFormats)) {
            $message = 'Invalid format "'.$format.'" specified.'
                .' The format should be one of the following: "'.
                implode('", "', $legalFormats).'".';
            $code = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        
        $dataFormat = '';
        if (strcmp($format, 'php') === 0) {
            $dataFormat = 'json';
        } else {
            $dataFormat = $format;
        }
        
        return $dataFormat;
    }
    
    protected function processFormsArgument($forms)
    {
        if (!isset($forms)) {
            $forms = array();
        } else {
            if (!is_array($forms)) {
                $message = 'The forms argument has invalid type "'.gettype($forms)
                    .'"; it should be an array.';
                $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } else { // @codeCoverageIgnore
                foreach ($forms as $form) {
                    $type = gettype($form);
                    if (strcmp($type, 'string') !== 0) {
                        $message = 'A form with type "'.$type.'" was found in the forms array.'.
                            ' Forms should be strings.';
                        $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT);
                    } // @codeCoverageIgnore
                }
            }
        }
        
        return $forms;
    }

    protected function processImportDataArgument($data, $dataName, $format)
    {
        if (!isset($data)) {
            $message = "No value specified for required argument '".$dataName."'.";
            $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT);
        } elseif ($format === 'php') {
            if (!is_array($data)) {
                $message = "Argument '".$dataName."' has type '".gettype($data)."'"
                    .", but should be an array.";
                $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
            $data = json_encode($data);
            
            $jsonError = json_last_error();
            
            switch ($jsonError) {
                case JSON_ERROR_NONE:
                    break;
                default:
                    $message =  'JSON error ('.$jsonError.') "'. json_last_error_msg().
                    '"'." while processing argument '".$dataName."'.";
                    $this->errorHandler->throwException($message, ErrorHandlerInterface::JSON_ERROR);
                    break; // @codeCoverageIgnore
            }
        } else { // All other formats
            if (gettype($data) !== 'string') {
                $message = "Argument '".$dataName."' has type '".gettype($data)."'"
                    .", but should be a string.";
                $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        }
        
        return $data;
    }
    
    /**
     * Checks the result returned from the REDCap API for non-export methods.
     * PHPCap is set to return errors from REDCap using JSON, so the result
     * string is checked to see if there is a JSON format error, and if so,
     * and exception is thrown using the error message returned from the
     * REDCap API.
     *
     * @param string $result a result returned from the REDCap API, which
     *     should be for a non-export method.
     */
    protected function processNonExportResult(& $result)
    {
        $matches = array();
        #$hasMatch = preg_match('/^[\s]*{"error":[\s]*"(.*)"}[\s]*$/', $result, $matches);
        $hasMatch = preg_match(self::JSON_RESULT_ERROR_PATTERN, $result, $matches);
        if ($hasMatch === 1) {
            // note: $matches[0] is the complete string that matched
            //       $matches[1] is just the error message part
            $message = $matches[1];
            $message = str_replace('\"', '"', $message);
            $message = str_replace('\n', "\n", $message);
             
            $code    = ErrorHandlerInterface::REDCAP_API_ERROR;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
    }
    
    
    protected function processOverrideArgument($override)
    {
        if ($override == null) {
            $override = false;
        } else {
            if (gettype($override) !== 'boolean') {
                $message = 'Invalid type for override. It should be a boolean (true or false),'
                    .' but has type: '.gettype($override).'.';
                $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        }
        
        if ($override === true) {
            $override = 1;
        } else {
            $override = 0;
        }
        
        return $override;
    }
    
    protected function processOverwriteBehaviorArgument($overwriteBehavior)
    {
        if (!isset($overwriteBehavior)) {
            $overwriteBehavior = 'normal';
        } elseif ($overwriteBehavior !== 'normal' && $overwriteBehavior !== 'overwrite') {
            $message = 'Invalid value "'.$overwriteBehavior.'" specified for overwriteBehavior.'.
                " Valid values are 'normal' and 'overwrite'.";
            $code = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        
        return $overwriteBehavior;
    }
    
    protected function processRawOrLabelArgument($rawOrLabel)
    {
        if (!isset($rawOrLabel)) {
            $rawOrLabel = 'raw';
        } else {
            if ($rawOrLabel !== 'raw' && $rawOrLabel !== 'label') {
                $message =   'Invalid value "'.$rawOrLabel.'" specified for rawOrLabel.'
                    ." Valid values are 'raw' and 'label'.";
                    $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        }
        return $rawOrLabel;
    }
    
    
    protected function processRawOrLabelHeadersArgument($rawOrLabelHeaders)
    {
        if (!isset($rawOrLabelHeaders)) {
            $rawOrLabelHeaders = 'raw';
        } else {
            if ($rawOrLabelHeaders !== 'raw' && $rawOrLabelHeaders !== 'label') {
                $message = 'Invalid value "'.$rawOrLabelHeaders.'" specified for rawOrLabelHeaders.'
                    ." Valid values are 'raw' and 'label'.";
                $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        }
        return $rawOrLabelHeaders;
    }
    
    
    protected function processRecordIdArgument($recordId, $required = true)
    {
        if (!isset($recordId)) {
            if ($required) {
                $message = 'No record ID specified.';
                $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        } elseif (!is_string($recordId) && !is_int($recordId)) {
            $message = 'The record ID has type "'.gettype($recordId)
                .'", but it should be a string or integer.';
                $code = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        }  // @codeCoverageIgnore
        
        return $recordId;
    }
    
    protected function processRecordIdsArgument($recordIds)
    {
        if (!isset($recordIds)) {
            $recordIds = array();
        } else {
            if (!is_array($recordIds)) {
                $message = 'The record IDs argument has type "'.gettype($recordIds)
                    .'"; it should be an array.';
                $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } else { // @codeCoverageIgnore
                foreach ($recordIds as $recordId) {
                    $type = gettype($recordId);
                    if (strcmp($type, 'integer') !== 0 && strcmp($type, 'string') !== 0) {
                        $message = 'A record ID with type "'.$type.'" was found.'
                            .' Record IDs should be integers or strings.';
                            $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                        $this->errorHandler->throwException($message, $code);
                    } // @codeCoverageIgnore
                }
            }
        }
        return $recordIds;
    }
    

    
    protected function processRepeatInstanceArgument($repeatInstance)
    {
        if (!isset($repeatInstance)) {
            ; // Might be OK
        } elseif (!is_int($repeatInstance)) {
            $message = 'The repeat instance has type "'.gettype($repeatInstance)
                .'", but it should be an integer.';
            $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        
        return $repeatInstance;
    }
    

    protected function processReportIdArgument($reportId)
    {
        if (!isset($reportId)) {
            $message = 'No report ID specified for export.';
            $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore

        if (is_string($reportId)) {
            if (!preg_match('/^[0-9]+$/', $reportId)) {
                $message = 'Report ID "'.$reportId.'" is non-numeric string.';
                $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        } elseif (is_int($reportId)) {
            if ($reportId < 0) {
                $message = 'Report ID "'.$reportId.'" is a negative integer.';
                $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        } else {
            $message = 'The report ID has type "'.gettype($reportId)
                .'", but it should be an integer or a (numeric) string.';
                $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        
        return $reportId;
    }
    

    protected function processReturnContentArgument($returnContent, $forceAutoNumber)
    {
        if (!isset($returnContent)) {
            $returnContent = 'count';
        } elseif ($returnContent === 'auto_ids') {
            if ($forceAutoNumber !== true) {
                $message = "'auto_ids' specified for returnContent,"
                    ." but forceAutoNumber was not set to true;"
                    ." 'auto_ids' can only be used when forceAutoNumber is set to true.";
                $code = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        } elseif ($returnContent !== 'count' && $returnContent !== 'ids') {
            $message = "Invalid value '".$returnContent."' specified for returnContent.".
                    " Valid values are 'count', 'ids' and 'auto_ids'.";
            $code = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
    
        return $returnContent;
    }
    
    protected function processReturnMetadataOnlyArgument($returnMetadataOnly)
    {
        if ($returnMetadataOnly== null) {
            $returnMetadataOnly= false;
        } else {
            if (gettype($returnMetadataOnly) !== 'boolean') {
                $message = 'Invalid type for returnMetadataOnly.'
                    .' It should be a boolean (true or false),'
                    .' but has type: '.gettype($returnMetadataOnly).'.';
                $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
                $this->errorHandler->throwException($message, $code);
            } // @codeCoverageIgnore
        }
        return $returnMetadataOnly;
    }
    
    protected function processSslVerifyArgument($sslVerify)
    {
        if (isset($sslVerify) && gettype($sslVerify) !== 'boolean') {
            $message = 'The value for $sslVerify must be a boolean (true/false), but has type: '
                .gettype($sslVerify);
            $code = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        return $sslVerify;
    }
    
    
    protected function processTypeArgument($type)
    {
        if (!isset($type)) {
            $type = 'flat';
        }
        $type = strtolower(trim($type));
        
        if (strcmp($type, 'flat') !== 0 && strcmp($type, 'eav') !== 0) {
            $message = "Invalid type '".$type."' specified. Type should be either 'flat' or 'eav'";
            $code    = ErrorHandlerInterface::INVALID_ARGUMENT;
            $this->errorHandler->throwException($message, $code);
        } // @codeCoverageIgnore
        return $type;
    }
}
PHPCap API documentation generated by ApiGen