class-ld-rest-quiz-statistics-controller.php 49.1 KB
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
<?php
/**
 * LearnDash REST API Quiz Statistics Controller.
 *
 * @since 3.3.0
 * @package LearnDash\REST\V2
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ( ! class_exists( 'LD_REST_Quiz_Statistics_Controller_V2' ) ) && class_exists( 'WP_REST_Controller' ) ) {

	/**
	 * Class LearnDash REST API Quiz Statistics Controller.
	 *
	 * @since 3.3.0
	 * @uses WP_REST_Controller
	 */
	class LD_REST_Quiz_Statistics_Controller_V2 extends WP_REST_Controller implements Iterator /* phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound */ {
		/**
		 * API version.
		 *
		 * @var string
		 */
		private $version;

		/**
		 * Records per page.
		 *
		 * @var int
		 */
		private $per_page;

		/**
		 * Page number currently being viewed.
		 *
		 * @var int
		 */
		private $page;

		/**
		 * Statistics refs list for current request.
		 *
		 * @var array
		 */
		private $stat_refs = array();

		/**
		 * Statistics refs count.
		 *
		 * @var int
		 */
		private $stat_refs_count = 0;

		/**
		 * Pointer for traversing over stat refs.
		 *
		 * @var int
		 */
		private $position = 0;

		/**
		 * Request object.
		 *
		 * @var WP_REST_Request
		 */
		private $request;

		/**
		 * User quiz data list.
		 * This will act as repository of information to
		 * avoid repetitive lookups.
		 *
		 * @var array
		 */
		private $user_quiz_data = array();

		/**
		 * Users to query for statistics.
		 *
		 * @var array
		 */
		private $users_for_stats = null;

		/**
		 * Constructor.
		 *
		 * @since 3.3.0
		 */
		public function __construct() {

			$this->version   = 'v2';
			$this->namespace = LEARNDASH_REST_API_NAMESPACE . '/' . $this->version;
			$this->rest_base = $this->get_rest_base( 'quizzes-statistics' );
		}

		/**
		 * Retrieve current node.
		 *
		 * @since 3.3.0
		 *
		 * @return mixed
		 */
		public function current() {

			return $this->stat_refs[ $this->position ];
		}

		/**
		 * Retrieve next node
		 *
		 * @since 3.3.0
		 */
		public function next() {

			++$this->position;
		}

		/**
		 * Retrieve current position of traversal pointer.
		 *
		 * @since 3.3.0
		 *
		 * @return bool|float|int|string|null
		 */
		public function key() {

			return $this->position;
		}

		/**
		 * Check if node is valid.
		 *
		 * @since 3.3.0
		 *
		 * @return bool
		 */
		public function valid() {
			return isset( $this->stat_refs[ $this->position ] );
		}

		/**
		 * Reset the pointer to first node.
		 *
		 * @since 3.3.0
		 *
		 * @return void
		 */
		public function rewind() {

			$this->position = 0;
		}

		/**
		 * Find the statistics record in memory.
		 *
		 * @since 3.3.0
		 *
		 * @param int $stat_ref_id Statistics reference ID.
		 *
		 * @return null|WpProQuiz_Model_StatisticRefModel
		 */
		public function find( $stat_ref_id = 0 ) {
			$found = null;

			foreach ( $this->stat_refs as $record ) {
				if ( $stat_ref_id === (int) $record->getStatisticRefId() ) {
					$found = $record;
					break;
				}
			}

			return $found;
		}

		/**
		 * Register API routes.
		 *
		 * @since 3.3.0
		 */
		public function register_routes() {
			if ( version_compare( PHP_VERSION, '7.3', '<' ) ) {
				return;
			}

			add_filter( 'rest_request_before_callbacks', array( $this, 'pre_callback_ops' ), 10, 3 );
			add_filter( 'rest_request_after_callbacks', array( $this, 'post_callback_ops' ), 10, 3 );
			add_filter( 'learndash_rest_statistic_response', array( $this, 'statistic_response_embed_links' ), 10, 1 );
			add_filter( 'learndash_rest_statistic_question_response', array( $this, 'statistic_question_response_embed_links' ), 10, 1 );

			foreach ( $this->routes() as $route => $route_args ) {
				register_rest_route(
					$this->namespace,
					'/' . $route,
					$route_args
				);
			}
		}

		/**
		 * Set the current request object in property.
		 * Also includes the necessary files.
		 *
		 * @since 3.3.0
		 *
		 * @param WP_REST_Response $response Response object.
		 * @param array            $handler  Route handler used for the request.
		 * @param WP_REST_Request  $request  Request object.
		 *
		 * @return WP_REST_Response Filtered response. This will have no modification in this case.
		 */
		public function pre_callback_ops( $response, $handler, $request ) {
			if ( $this->is_qs_endpoint( $request ) ) {
				$this->reset_state();

				/**
				 * Include necessary classes.
				 */
				include untrailingslashit( LEARNDASH_LMS_PLUGIN_DIR ) . '/includes/interfaces/interface-ldlms-answer.php';
				include untrailingslashit( LEARNDASH_LMS_PLUGIN_DIR ) . '/includes/classes/answer-types/class-ldlms-base-answer-type.php';
				include untrailingslashit( LEARNDASH_LMS_PLUGIN_DIR ) . '/includes/classes/answer-types/class-ldlms-sort-answer-type.php';
				include untrailingslashit( LEARNDASH_LMS_PLUGIN_DIR ) . '/includes/classes/answer-types/class-ldlms-assessment-answer-type.php';
				include untrailingslashit( LEARNDASH_LMS_PLUGIN_DIR ) . '/includes/classes/answer-types/class-ldlms-cloze-answer-type.php';
				include untrailingslashit( LEARNDASH_LMS_PLUGIN_DIR ) . '/includes/classes/answer-types/class-ldlms-free-answer-type.php';
				include untrailingslashit( LEARNDASH_LMS_PLUGIN_DIR ) . '/includes/classes/answer-types/class-ldlms-essay-answer-type.php';

				/**
				 * Add necessary filters for statistics query.
				 */
				add_filter( 'learndash_statrefs_joins', array( $this, 'join_quiz_master_and_postmeta' ) );
				add_filter( 'learndash_statrefs_where', array( $this, 'statistics_ref_where' ) );
				add_filter( 'learndash_statrefs_where', array( $this, 'statistics_ref_users_where' ), 20 );
				add_filter( 'learndash_statrefs_where', array( $this, 'statistics_ref_quiz_where' ), 25 );
				add_filter( 'learndash_statrefs_where', array( $this, 'statistics_ref_duration_where' ), 25 );

				$this->request = $request;
				$this->fetch_stat_refs();
				$this->stat_refs = array_values( $this->stat_refs );
			}

			return $response;
		}

		/**
		 * Perform operations after the callback is executed.
		 *
		 * @since 3.3.0
		 *
		 * @param WP_REST_Response $response Response object.
		 * @param array            $handler  Route handler used for the request.
		 * @param WP_REST_Request  $request  Request object.
		 *
		 * @return WP_REST_Response Filtered response. This will have no modification in this case.
		 */
		public function post_callback_ops( $response, $handler, $request ) {
			if ( $this->is_qs_endpoint( $request ) ) {
				$this->restore_state();
			}
			return $response;
		}

		/**
		 * Retrieve list of quiz statistics.
		 *
		 * @since 3.3.0
		 *
		 * @param WP_REST_Request $request Request object from REST.
		 *
		 * @return WP_Error|WP_REST_Response
		 */
		public function get_items( $request ) {
			if ( ! $this->stat_refs ) {
				return new WP_Error( 404, __( 'No records found for this request.', 'learndash' ) );
			}

			$stats_list = array();

			do {

				$request_clone = clone $request;
				$request_clone->set_param( 'id', $this->current()->getStatisticRefId() );
				$statistics   = $this->get_item( $request_clone );
				$stat_data    = $statistics->get_data();
				$stats_list[] = $stat_data;

				$this->next();
			} while ( $this->valid() );

			$response = rest_ensure_response( $stats_list );

			// Add the pagination links to response header.
			$total_items = $this->stat_refs_count;
			$max_pages   = ceil( $total_items / (int) $this->per_page );

			if ( $this->page > $max_pages && $total_items > 0 ) {
				return new WP_Error( 'rest_post_invalid_page_number', __( 'The page number requested is larger than the number of pages available.', 'learndash' ), array( 'status' => 400 ) );
			}

			$response->header( 'X-WP-Total', (int) $total_items );
			$response->header( 'X-WP-TotalPages', (int) $max_pages );

			$request_params = $request->get_query_params();
			$base           = add_query_arg( $request_params, rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );

			if ( $this->page > 1 ) {
				$prev_page = $this->page - 1;

				if ( $prev_page > $max_pages ) {
					$prev_page = $max_pages;
				}

				$prev_link = add_query_arg( 'page', $prev_page, $base );
				$response->link_header( 'prev', $prev_link );
			}
			if ( $max_pages > $this->page ) {
				$next_page = $this->page + 1;
				$next_link = add_query_arg( 'page', $next_page, $base );

				$response->link_header( 'next', $next_link );
			}

			return $response;
		}

		/**
		 * Retrieve a single item from statistics based on ID.
		 *
		 * @since 3.3.0
		 *
		 * @param WP_REST_Request $request Request object from REST.
		 *
		 * @return WP_Error|WP_REST_Response
		 */
		public function get_item( $request ) {
			if ( ! $this->valid() ) {
				return new WP_Error( 404, __( 'Invalid entry', 'learndash' ) );
			}

			$stat_ref_id = $this->current()->getStatisticRefId();
			$stat_object = $this->stat_response_object();

			$stat_object = apply_filters( 'learndash_rest_statistic_response', (array) $stat_object );
			return new WP_REST_Response( $stat_object );
		}

		/**
		 * Retrieve list of questions for a particular stat ref ID.
		 *
		 * @since 3.3.0
		 *
		 * @param WP_REST_Request $request Request object from REST.
		 *
		 * @return WP_Error|WP_REST_Response
		 */
		public function get_questions( $request ) {
			if ( ! $this->valid() ) {
				return new WP_Error( 404, __( 'Invalid entry', 'learndash' ) );
			}

			$stat_ref_id = $this->current()->getStatisticRefId();

			$question_id      = 0;
			$stat_question_id = $request->get_param( 'id' );
			if ( ! empty( $stat_question_id ) ) {
				list( $ref_id, $question_id ) = explode( '_', $stat_question_id );
				if ( absint( $ref_id ) === $stat_ref_id ) {
					$question_id = absint( $question_id );
				} else {
					$question_id = 0;
				}
			}

			try {
				$stat_questions  = array();
				$question_mapper = new WpProQuiz_Model_QuestionMapper();
				$statistic       = ( new WpProQuiz_Model_StatisticMapper() )->fetchAllByRef( $stat_ref_id );
				$questions       = $question_mapper->fetchByStatId( $stat_ref_id, $question_id, $this->per_page, $this->per_page * ( $this->page - 1 ) );
				$questions_count = $question_mapper->fetchByStatIdCount( $stat_ref_id, $question_id );

				foreach ( $questions as $question ) {
					$stat_model = $this->get_statistics_mode_from_list( $statistic, 'getQuestionId', (int) $question->getId() );

					$answer_type_obj = $this->make_answer_obj(
						$question->getAnswerType(),
						array(
							$question,
							$stat_model->getAnswerData(),
							$this->current(),
						)
					);

					$answer_type_obj->setup();

					$question_response = new stdClass();

					$question_response->id            = $stat_ref_id . '_' . $question->getId(); // Need to have a unique ID.
					$question_response->statistic     = (int) $stat_ref_id;
					$question_response->quiz          = $this->getQuizId();
					$question_response->question      = learndash_get_question_post_by_pro_id( $question->getId() ) ? learndash_get_question_post_by_pro_id( $question->getId() ) : null;
					$question_response->question_type = $question->getAnswerType();
					$question_response->points_scored = $this->get_count( $statistic, 'getPoints' );
					$question_response->points_total  = (int) $this->current()->getMapper()->fetchTotalPoints( $this->current()->getStatisticRefId() );
					$question_response->answers       = $answer_type_obj->get_answers();
					$question_response->student       = (object) $answer_type_obj->get_student_answers();

					$question_response = (array) $question_response;

					/**
					 * Filters the response object for each question.
					 *
					 * @since 3.3.0
					 *
					 * @param array                             $question_response Response array for question.
					 * @param WpProQuiz_Model_Question          $question          Question object.
					 * @param string                            $student_answers   Submitted answer data by student.
					 * @param WpProQuiz_Model_StatisticRefModel $stat_ref_model    Statistics ref model.
					 */
					$question_response = apply_filters(
						'learndash_rest_statistic_question_response',
						$question_response,
						$question,
						$stat_model->getAnswerData(),
						$this->current()
					);

					$stat_questions[] = $question_response;
				}

				$response = rest_ensure_response( $stat_questions );

				// Add the pagination links to response header.
				$total_items = $questions_count;
				$max_pages   = ceil( $total_items / (int) $this->per_page );

				if ( $this->page > $max_pages && $total_items > 0 ) {
					return new WP_Error( 'rest_post_invalid_page_number', __( 'The page number requested is larger than the number of pages available.', 'learndash' ), array( 'status' => 400 ) );
				}

				$response->header( 'X-WP-Total', (int) $total_items );
				$response->header( 'X-WP-TotalPages', (int) $max_pages );

				$request_params = $request->get_query_params();
				$base           = add_query_arg( $request_params, rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );

				if ( $this->page > 1 ) {
					$prev_page = $this->page - 1;

					if ( $prev_page > $max_pages ) {
						$prev_page = $max_pages;
					}

					$prev_link = add_query_arg( 'page', $prev_page, $base );
					$response->link_header( 'prev', $prev_link );
				}
				if ( $max_pages > $this->page ) {
					$next_page = $this->page + 1;
					$next_link = add_query_arg( 'page', $next_page, $base );

					$response->link_header( 'next', $next_link );
				}

				return $response;

			} catch ( Throwable $throwable ) { // phpcs:ignore PHPCompatibility.Interfaces.NewInterfaces.throwableFound
				// Executed only in PHP 7+, will not match in PHP 5.x.
				$code = $throwable->getCode() > 0 ? $throwable->getCode() : 400;

				return new WP_Error( $code, $throwable->getMessage() );
			} catch ( Exception $exception ) {
				// Executed only in PHP 5.x. Will not be reached in PHP 7+.
				$code = $exception->getCode() > 0 ? $exception->getCode() : 400;

				return new WP_Error( $code, $exception->getMessage() );
			}
		}

		/**
		 * Permission callback for quiz-statistics endpoint.
		 *
		 * @since 3.3.0
		 *
		 * @param WP_REST_Request $request Request object.
		 *
		 * @return bool If stats can be accessed by user.
		 */
		public function can_access_stats( $request ) {
			if ( ! current_user_can( 'wpProQuiz_show_statistics' ) ) {
				return false;
			}

			// Check we have a valid Quiz ID.
			$quiz_id = $request->get_param( 'quiz' );
			if ( empty( $quiz_id ) ) {
				return false;
			}

			// Check the Quiz has Statistics enabled.
			$quiz_pro_statistics_on = learndash_get_setting( $quiz_id, 'statisticsOn', true );
			if ( ! $quiz_pro_statistics_on ) {
				return false;
			}

			$stat_ref_id = $request->get_param( 'statistic' );
			$stat_users  = (array) $this->users_for_stats();

			if ( $stat_ref_id && $this->valid() ) {
				$stat_user  = (int) $this->current()->getUserId();
				$stat_users = array_map( 'absint', $stat_users );
				return empty( $stat_users ) || in_array( $stat_user, $stat_users, true );
			}

			return true;
		}

		/**
		 * Permission callback for quiz-statistics endpoint.
		 *
		 * @since 3.3.0
		 *
		 * @param WP_REST_Request $request Request object.
		 *
		 * @return bool If stats can be accessed by user.
		 */
		public function can_access_stats_questions( $request ) {
			if ( ! current_user_can( 'wpProQuiz_show_statistics' ) ) {
				return false;
			}

			// Check we have a valid Quiz ID.
			$quiz_id = $request->get_param( 'quiz' );
			if ( empty( $quiz_id ) ) {
				return false;
			}

			// Check the Quiz has Statistics enabled.
			$quiz_pro_statistics_on = learndash_get_setting( $quiz_id, 'statisticsOn', true );
			if ( ! $quiz_pro_statistics_on ) {
				return false;
			}

			$stat_ref_id = $request->get_param( 'statistic' );
			$stat_users  = (array) $this->users_for_stats();

			if ( $stat_ref_id && $this->valid() ) {
				$stat_user  = (int) $this->current()->getUserId();
				$stat_users = array_map( 'absint', $stat_users );
				return empty( $stat_users ) || in_array( $stat_user, $stat_users, true );
			}

			return true;
		}

		/**
		 * Add the embed links to quiz statistic response item.
		 *
		 * @since 3.3.0
		 *
		 * @param array $response    Response object in which link will be added.
		 *
		 * @return array
		 */
		public function statistic_response_embed_links( array $response ) {

			if ( ( isset( $response['quiz'] ) ) && ( ! empty( $response['quiz'] ) ) ) {

				$quiz_rest_base       = sprintf( '%s/%s/%d', $this->namespace, $this->get_rest_base( 'quizzes' ), absint( $response['quiz'] ) );
				$statistics_rest_base = $quiz_rest_base . '/' . $this->get_rest_base( 'quizzes-statistics' );

				$response['_links']['collection'] = array(
					array(
						'href' => rest_url( $statistics_rest_base ),
					),
				);

				if ( ( isset( $response['id'] ) ) && ( ! empty( $response['id'] ) ) ) {
					$response['_links']['self'] = array(
						array(
							'href' => rest_url( $statistics_rest_base . '/' . absint( $response['id'] ) ),
						),
					);

					$response['_links']['questions'] = array(
						array(
							'href'       => rest_url( $statistics_rest_base . '/' . absint( $response['id'] ) . '/questions' ),
							'embeddable' => true,
						),
					);
				}

				if ( learndash_get_post_type_slug( 'quiz' ) === get_post_type( absint( $response['quiz'] ) ) ) {
					$response['_links']['quiz'] = array(
						array(
							'href'       => rest_url( $quiz_rest_base ),
							'embeddable' => true,
						),
					);
				}
			}

			if ( ( isset( $response['user'] ) ) && ( ! empty( $response['user'] ) ) ) {
				$user = get_user_by( 'id', $response['user'] );
				if ( ( $user ) && ( is_a( $user, 'WP_User' ) ) ) {
					$response['_links']['user'] = array(
						array(
							// I hate that WP doesn't have some defined vars to know the namespace and version.
							'href'       => rest_url( 'wp/v2/users/' . $response['user'] ),
							'embeddable' => true,
						),
					);
				}
			}

			return $response;
		}

		/**
		 * Add the embed links to quiz statistic question response item.
		 *
		 * @since 3.3.0
		 *
		 * @param array $response    Response object in which link will be added.
		 *
		 * @return array
		 */
		public function statistic_question_response_embed_links( array $response ) {

			if ( ( isset( $response['quiz'] ) ) && ( ! empty( $response['quiz'] ) ) && ( learndash_get_post_type_slug( 'quiz' ) === get_post_type( absint( $response['quiz'] ) ) ) ) {

				$quiz_rest_base = sprintf( '%s/%s/%d', $this->namespace, $this->get_rest_base( 'quizzes' ), absint( $response['quiz'] ) );

				$statistics_collection_rest_base = sprintf( '%s/%s', $quiz_rest_base, $this->get_rest_base( 'quizzes-statistics' ) );

				$statistics_single_rest_base = sprintf( '%s/%d', $statistics_collection_rest_base, absint( $response['statistic'] ) );

				$statistics_questions_collection_rest_base = sprintf( '%s/%s', $statistics_single_rest_base, $this->get_rest_base( 'quizzes-statistics-questions' ) );

				$response['_links']['collection'] = array(
					array(
						'href' => rest_url( $statistics_questions_collection_rest_base ),
					),
				);

				if ( ( isset( $response['id'] ) ) && ( ! empty( $response['id'] ) ) ) {
					$response['_links']['self'] = array(
						array(
							'href' => rest_url( $statistics_questions_collection_rest_base . '/' . $response['id'] ),
						),
					);
				}

				if ( ( isset( $response['statistic'] ) ) && ( ! empty( $response['statistic'] ) ) ) {
					$response['_links']['statistic'] = array(
						array(
							'href' => rest_url( $statistics_single_rest_base ),
						),
					);
				}

				if ( ( isset( $response['question_type'] ) ) && ( ! empty( $response['question_type'] ) ) ) {
					$question_type_rest_base = $this->namespace . '/' . $this->get_rest_base( 'question-types' );

					$response['_links'][ $this->get_rest_base( 'question-types' ) ] = array(
						array(
							'href'       => rest_url( $question_type_rest_base . '/' . $response['question_type'] ),
							'embeddable' => true,
						),
					);
				}

				$response['_links']['quiz'] = array(
					array(
						'href'       => rest_url( $quiz_rest_base ),
						'embeddable' => true,
					),
				);
			}

			if ( ( isset( $response['question'] ) ) && ( ! empty( $response['question'] ) ) ) {
				$question_rest_base = sprintf( '%s/%s/%d', $this->namespace, $this->get_rest_base( 'questions' ), absint( $response['question'] ) );

				$response['_links']['question'] = array(
					array(
						// I hate that WP doesn't have some defined vars to know the namespace and version.
						'href'       => rest_url( $question_rest_base ),
						'embeddable' => true,
					),
				);
			}

			if ( ( isset( $response['user'] ) ) && ( ! empty( $response['user'] ) ) ) {
				$user = get_user_by( 'id', $response['user'] );
				if ( ( $user ) && ( is_a( $user, 'WP_User' ) ) ) {
					$response['_links']['user'] = array(
						array(
							// I hate that WP doesn't have some defined vars to know the namespace and version.
							'href'       => rest_url( 'wp/v2/users/' . $response['user'] ),
							'embeddable' => true,
						),
					);
				}
			}

			return $response;
		}

		/**
		 * Join query for fetching statistics for which quiz_setting is enabled.
		 * Quiz > Settings > Quiz statistics > Enable front end display
		 *
		 * @since 3.3.0
		 *
		 * @param string $join Join clause for query.
		 *
		 * @return string
		 */
		public function join_quiz_master_and_postmeta( $join ) {
			global $wpdb;

			return $join;
		}

		/**
		 * Filter the where clause of the query to fetch statistics refs.
		 *
		 * @since 3.3.0
		 *
		 * @param string $where Where clause.
		 *
		 * @return string
		 */
		public function statistics_ref_where( $where ) {
			return $where;
		}

		/**
		 * Filter the where clause of the query to fetch statistics refs
		 * based on user IDs.
		 *
		 * @since 3.3.0
		 *
		 * 1. Admins have access to all statistics.
		 * 2. Group leaders will have access to statistics of only those
		 *    users which belong to their groups.
		 * 3. Other logged in users will have access to only their stats.
		 * 4. Logged out user cannot access stats.
		 *
		 * @param string $where Where clause for query.
		 *
		 * @return string
		 */
		public function statistics_ref_users_where( $where ) {
			global $wpdb;

			$user_id = $this->request->get_param( 'user' );
			if ( $user_id ) {
				$where .= $wpdb->prepare( " AND statref.user_id=%d ", (int) $user_id ); //phpcs:ignore
			} else {

				$users = $this->users_for_stats();

				if ( ( $users ) ) {
					$how_many     = count( $users );
					$placeholders = array_fill( 0, $how_many, '%d' );
					$format       = implode( ', ', $placeholders );
					$where       .= $wpdb->prepare( " AND statref.user_id IN ($format) ", $users ); //phpcs:ignore
				}
			}

			return $where;
		}

		/**
		 * If quiz id is passed explicitly via request, filter the results.
		 *
		 * @since 3.3.0
		 *
		 * @param string $where Where clause.
		 *
		 * @return string
		 */
		public function statistics_ref_quiz_where( $where ) {
			global $wpdb;

			$quiz_id = $this->request->get_param( 'quiz' );
			if ( $quiz_id ) {
				$quiz_pro_id = get_post_meta( $quiz_id, 'quiz_pro_id', true );
				$quiz_pro_id = absint( $quiz_pro_id );
				if ( ! empty( $quiz_pro_id ) ) {
					$where .= $wpdb->prepare( " AND statref.quiz_id=%d ", (int) $quiz_pro_id ); //phpcs:ignore
				}
			}

			return $where;
		}

		/**
		 * If before date and/or after date are passed, add
		 * conditions in where clause.
		 *
		 * @since 3.3.0
		 *
		 * @param string $where WHERE Clause for query.
		 *
		 * @return string
		 */
		public function statistics_ref_duration_where( $where ) {
			global $wpdb;
			$after_date  = $this->request->get_param( 'after' );
			$before_date = $this->request->get_param( 'before' );

			if ( $after_date ) {
				$s_date = strtotime( $after_date );
				$where .= ( false !== $s_date ) ? $wpdb->prepare( ' AND statref.create_time >= %s', $s_date ) : '';
			}

			if ( $before_date ) {
				$e_date = strtotime( $before_date );
				$where .= ( false !== $e_date ) ? $wpdb->prepare( ' AND statref.create_time <= %s', $e_date ) : '';
			}

			return $where;
		}

		/**
		 * Return the route information in form of an array.
		 *
		 * @since 3.3.0
		 *
		 * @return array
		 */
		private function routes() {
			$quiz_rest_base                                      = $this->get_rest_base( 'quizzes' ) . '/(?P<quiz>[\d]+)/' . $this->get_rest_base( 'quizzes-statistics' );
			$routes[ $quiz_rest_base ]                           = array(
				'args'   => array(
					'quiz' => array(
						'description' => sprintf(
							// translators: placeholder: Quiz.
							esc_html_x(
								'Unique %s identifier for the object.',
								'placeholder: Quiz',
								'learndash'
							),
							LearnDash_Custom_Label::get_label( 'quiz' )
						),
						'type'        => 'integer',
						'required'    => true,
					),
				),
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_items' ),
					'permission_callback' => array( $this, 'can_access_stats' ),
					'args'                => $this->get_collection_params_statistics(),
				),
				'schema' => array( $this, 'get_stats_schema' ),
			);
			$routes[ $quiz_rest_base . '/(?P<statistic>[\d]+)' ] = array(
				'args' => array(
					'quiz' => array(
						'description' => sprintf(
							// translators: placeholder: Quiz.
							esc_html_x(
								'Unique %s identifier for the object.',
								'placeholder: Quiz',
								'learndash'
							),
							LearnDash_Custom_Label::get_label( 'quiz' )
						),
						'type'        => 'integer',
						'required'    => true,
					),
				),
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_item' ),
					'permission_callback' => array( $this, 'can_access_stats' ),
				),
			);

			$quizzes_statistics_questions_base            = $quiz_rest_base . '/(?P<statistic>[\d]+)/' . $this->get_rest_base( 'quizzes-statistics-questions' );
			$routes[ $quizzes_statistics_questions_base ] = array(
				'args'   => array(
					'quiz'      => array(
						'description' => sprintf(
							// translators: placeholder: Quiz.
							esc_html_x(
								'Unique %s identifier for the object.',
								'placeholder: Quiz',
								'learndash'
							),
							LearnDash_Custom_Label::get_label( 'quiz' )
						),
						'type'        => 'integer',
						'required'    => true,
					),
					'statistic' => array(
						'description' => sprintf(
							// translators: placeholder: Quiz.
							esc_html_x(
								'Unique %s Statistic identifier for the object.',
								'placeholder: Quiz',
								'learndash'
							),
							LearnDash_Custom_Label::get_label( 'quiz' )
						),
						'type'        => 'integer',
						'required'    => true,
					),
				),
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_questions' ),
					'permission_callback' => array( $this, 'can_access_stats_questions' ),
					'args'                => $this->get_collection_params_statistics_questions(),
				),
				'schema' => array( $this, 'get_stats_questions_schema' ),
			);

			$routes[ $quizzes_statistics_questions_base . '/(?P<id>[\w-]+)' ] = array(
				'args' => array(
					'quiz'      => array(
						'description' => sprintf(
							// translators: placeholder: Quiz.
							esc_html_x(
								'Unique %s identifier for the object.',
								'placeholder: Quiz',
								'learndash'
							),
							LearnDash_Custom_Label::get_label( 'quiz' )
						),
						'type'        => 'integer',
						'required'    => true,
					),
					'statistic' => array(
						'description' => sprintf(
							// translators: placeholder: Quiz.
							esc_html_x(
								'Unique %s Statistic identifier for the object.',
								'placeholder: Quiz',
								'learndash'
							),
							LearnDash_Custom_Label::get_label( 'quiz' )
						),
						'type'        => 'integer',
						'required'    => true,
					),
					'id'        => array(
						'description' => sprintf(
							// translators: placeholder: Quiz, Question.
							esc_html_x(
								'Unique %1$s Statistic %2$s identifier for the object.',
								'placeholder: Quiz, Question',
								'learndash'
							),
							LearnDash_Custom_Label::get_label( 'quiz' ),
							LearnDash_Custom_Label::get_label( 'question' )
						),
						'type'        => 'text',
						'required'    => true,
					),

				),
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_questions' ),
					'permission_callback' => array( $this, 'can_access_stats_questions' ),
				),
			);

			return $routes;
		}

		/**
		 * Check if the current endpoint is quiz statistics endpoint.
		 *
		 * @since 3.3.0
		 *
		 * @param WP_REST_Request $request Request object.
		 *
		 * @return bool
		 */
		private function is_qs_endpoint( WP_REST_Request $request ) {
			$is_qs_endpoint = false;

			$current_route = str_replace( trailingslashit( $this->namespace ), '', $request->get_route() );
			$routes        = array_keys( $this->routes() );

			foreach ( $routes as $route ) {
				if ( preg_match( '~' . $route . '~', ltrim( $current_route, '/' ) ) ) {
					$is_qs_endpoint = true;
					break;
				}
			}

			return $is_qs_endpoint;
		}

		/**
		 * Fetches expected parameters from request and sets
		 * the properties based on their values; else default
		 * will be assigned.
		 *
		 * @since 3.3.0
		 *
		 * @return void
		 */
		private function build_params() {

			$this->per_page = $this->request->get_param( 'per_page' ) ? $this->request->get_param( 'per_page' ) : (int) get_option( 'posts_per_page' );
			$this->page     = $this->request->get_param( 'page' ) ? $this->request->get_param( 'page' ) : 1;
		}

		/**
		 * Fetch the stat refs records for current request.
		 *
		 * @since 3.3.0
		 *
		 * @return void
		 */
		private function fetch_stat_refs() {
			$this->build_params();
			$stat_ref_id     = $this->request->get_param( 'statistic' );
			$stat_ref_mapper = new WpProQuiz_Model_StatisticRefMapper();

			if ( ! $stat_ref_id ) {
				$args = array(
					'limit'  => $this->per_page,
					'offset' => $this->per_page * ( $this->page - 1 ),
				);

				$order   = $this->request->get_param( 'order' );
				$orderby = $this->request->get_param( 'orderby' );
				if ( ( ! empty( $order ) ) && ( ! empty( $orderby ) ) ) {
					$args['order']   = $order;
					$args['orderby'] = $orderby;
				}

				$stat_refs             = $stat_ref_mapper->fetchSelected( $args );
				$this->stat_refs_count = $stat_ref_mapper->fetchSelectedCount( $args );

				if ( $stat_refs ) {
					foreach ( $stat_refs as $ref ) {
						$ref->setMapper( $stat_ref_mapper );
						$this->stat_refs[ $ref->getStatisticRefId() ] = $ref;
					}
				}

				return;
			}

			$this->stat_refs[ $stat_ref_id ] = $stat_ref_mapper->fetchAllByRef( $stat_ref_id );
			$this->stat_refs[ $stat_ref_id ] = $this->stat_refs[ $stat_ref_id ] ? $this->stat_refs[ $stat_ref_id ]->setMapper( $stat_ref_mapper ) : null;
		}

		/**
		 * User IDs for fetching statistics.
		 *
		 * @since 3.3.0
		 *
		 * 1. Admins have access to all statistics, thus null will be returned.
		 * 2. Group leaders will have access to statistics of only those
		 *    users which belong to their groups.
		 * 3. Other logged in users will have access to only their stats.
		 * 4. Logged out user cannot access stats.
		 */
		private function users_for_stats() {

			if ( ! is_null( $this->users_for_stats ) ) {
				return $this->users_for_stats;
			}

			if ( is_null( $this->request ) ) {
				return $this->users_for_stats;
			}

			$quiz_id = $this->request->get_param( 'quiz' );
			if ( empty( $quiz_id ) ) {
				$this->users_for_stats = array( 0 );
				return $this->users_for_stats;
			}

			if ( learndash_is_admin_user() ) {
				$this->users_for_stats = array();
			} elseif ( learndash_is_group_leader_user() ) {
				if ( learndash_get_group_leader_manage_courses() ) {
					/**
					 * If the Group Leader can manage_courses they have will access
					 * to all quizzes. So they are treated like the admin user.
					 */
					$this->users_for_stats = array();
				} else {
					/**
					 * Else we need to figure out of the quiz requested is part of a
					 * Course within Group managed by the Group Leader.
					 */
					$quiz_users     = array();
					$leader_courses = learndash_get_groups_administrators_courses( get_current_user_id() );
					if ( ! empty( $leader_courses ) ) {
						$quiz_courses = array();
						if ( 'yes' === LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Courses_Builder', 'shared_steps' ) ) {
							$quiz_courses = learndash_get_courses_for_step( $quiz_id, true );
						} else {
							$quiz_course = learndash_get_setting( $quiz_id, 'course' );
							if ( ! empty( $quiz_course ) ) {
								$quiz_courses = array( $quiz_course );
							}
						}

						if ( ! empty( $quiz_courses ) ) {
							$common_courses = array_intersect( $quiz_courses, $leader_courses );
							if ( ! empty( $common_courses ) ) {
								/**
								 * The following will get a list of all users within the Groups
								 * managed by the Group Leader. This list of users will be passed
								 * to the query logic to limit the selected rows.
								 *
								 * This is not 100% accurate because we don't limit the rows based
								 * on the associated courses. Consider if Shared Course steps is
								 * enabled and the quiz is part of two courses and those courses
								 * are associated with multiple groups. And the user is in both
								 * groups. So potentially we will pull in statistics records for
								 * the other course quizzes.
								 */
								$quiz_users = learndash_get_groups_administrators_users( get_current_user_id() );
							}
						}
					}

					if ( ! empty( $quiz_users ) ) {
						$this->users_for_stats = $quiz_users;
					} else {
						$this->users_for_stats = array( 0 );
					}
				}
			} else {
				// If here then non-admin and non-group leader user.
				$quiz_id = $this->request->get_param( 'quiz' );
				if ( ! empty( $quiz_id ) ) {
					if ( get_post_meta( $quiz_id, '_viewProfileStatistics', true ) ) {
						$this->users_for_stats = (array) get_current_user_id();
						return $this->users_for_stats;
					}
				}

				$this->users_for_stats = array( 0 );
			}

			return $this->users_for_stats;
		}

		/**
		 * Get correct/incorrect count for a particular statistics_ref_id.
		 *
		 * @since 3.3.0
		 *
		 * @param array  $stats Stats for particular statistic ref.
		 * @param string $type  Correct or incorrect count.
		 *
		 * @return integer
		 */
		private function get_count( array $stats, $type = 'getCorrectCount' ) {
			$count = 0;

			foreach ( $stats as $stat ) {
				$count = $count + $stat->$type();
			}

			return $count;
		}

		/**
		 * Prepare the single statistics object for API response.
		 *
		 * @since 3.3.0
		 *
		 * @return stdClass
		 */
		private function stat_response_object() {
			$stats               = ( new WpProQuiz_Model_StatisticMapper() )->fetchAllByRef( $this->current()->getStatisticRefId() );
			$stat_response       = new stdClass();
			$stat_response->id   = $this->current()->getStatisticRefId();
			$stat_response->quiz = $this->getQuizId();
			$stat_response->user = $this->current()->getUserId();
			$stat_response->date = $this->prepare_date_response( gmdate( 'Y-m-d H:i:s', $this->current()->getCreateTime() ) );

			$stat_response->answers_correct   = $this->get_count( $stats, 'getCorrectCount' );
			$stat_response->answers_incorrect = $this->get_count( $stats, 'getIncorrectCount' );
			$stat_response->points_scored     = $this->get_count( $stats, 'getPoints' );
			$stat_response->points_total      = (int) $this->current()->getMapper()->fetchTotalPoints( $this->current()->getStatisticRefId() );

			return $stat_response;
		}

		/**
		 * Get user's quiz details from usermeta.
		 *
		 * @since 3.3.0
		 *
		 * @return array
		 */
		private function get_user_quiz_details() {
			if ( isset( $this->user_quiz_data[ $this->current()->getUserId() ] ) ) {

				return $this->user_quiz_data[ $this->current()->getUserId() ];
			}

			$user_quizzes       = (array) get_user_meta( $this->current()->getUserId(), '_sfwd-quizzes', true );
			$user_quizzes_stats = array();
			/**
			 * We want to rebuild/re-index the quizzes listing to be by
			 * the statistics ref ID.
			 */
			if ( ! empty( $user_quizzes ) ) {
				foreach ( $user_quizzes as $user_quiz ) {
					if ( ( ! isset( $user_quiz['statistic_ref_id'] ) ) || ( empty( $user_quiz['statistic_ref_id'] ) ) ) {
						continue;
					}

					$statistic_ref_id                        = absint( $user_quiz['statistic_ref_id'] );
					$user_quizzes_stats[ $statistic_ref_id ] = $user_quiz;
				}
			}
			$this->user_quiz_data[ $this->current()->getUserId() ] = $user_quizzes_stats;

			return $this->user_quiz_data[ $this->current()->getUserId() ];
		}

		/**
		 * Get quiz id for current statistics.
		 *
		 * @since 3.3.0
		 *
		 * @return int
		 */
		private function getQuizId() {
			$quiz_data = $this->get_user_quiz_details();

			$current_stat_id = (int) $this->current()->getStatisticRefId();
			if ( isset( $quiz_data[ $current_stat_id ]['quiz'] ) ) {
				return $quiz_data[ $current_stat_id ]['quiz'];
			}

			return 0;
		}

		/**
		 * Build the answer type object and returns it.
		 * It throws exception for any invalid type which will
		 * be caught by callee.
		 *
		 * @since 3.3.0
		 *
		 * @param string $type Type of answer object we want to build.
		 * @param array  $args Argument for class constructor.
		 *
		 * @return LDLMS_Answer
		 * @throws Exception Exception for invalid type.
		 */
		private function make_answer_obj( $type, $args = array() ) {

			switch ( $type ) {

				case 'single':
				case 'multiple':
					$object = new ReflectionClass( LDLMS_Base_Answer_Type::class );
					return $object->newInstanceArgs( $args );

				case 'sort_answer':
				case 'matrix_sort_answer':
					$object = new ReflectionClass( LDLMS_Sort_Answer::class );
					return $object->newInstanceArgs( $args );

				case 'assessment_answer':
					$object = new ReflectionClass( LDLMS_Assessment_Answer::class );
					return $object->newInstanceArgs( $args );

				case 'cloze_answer':
					$object = new ReflectionClass( LDLMS_Cloze_Answer::class );
					return $object->newInstanceArgs( $args );

				case 'free_answer':
					$object = new ReflectionClass( LDLMS_Free_Answer::class );
					return $object->newInstanceArgs( $args );

				case 'essay':
					$object = new ReflectionClass( LDLMS_Essay_Answer::class );
					return $object->newInstanceArgs( $args );

				default:
					// translators: placeholder: question.
					throw new Exception( sprintf( esc_html_x( 'Invalid %s type supplied', 'placeholder: question', 'learndash' ), learndash_get_custom_label( 'question' ) ), 404 );
			}
		}

		/**
		 * Get WpProQuiz_Model_Statistic object from list of a particular stat.
		 *
		 * @since 3.3.0
		 *
		 * @param array  $stats    Statistics for the current ref id.
		 * @param string $method   Method to call.
		 * @param mixed  $expected Expected result.
		 *
		 * @return WpProQuiz_Model_Statistic|null
		 */
		private function get_statistics_mode_from_list( array $stats, $method, $expected ) {

			foreach ( $stats as $key => $stat ) {
				if ( $stat instanceof WpProQuiz_Model_Statistic && method_exists( $stat, $method ) ) {
					$result = $stat->$method();

					if ( $expected === $result ) {
						return $stats[ $key ];
					}
				}
			}

			return null;
		}

		/**
		 * Reset current state of an object and store current state
		 * in a global variable.
		 *
		 * This will be useful because if we pass embed parameter, same class
		 * will be called with a new request and Iterator pointers need to be
		 * reset at that time.
		 *
		 * @since 3.3.0
		 */
		private function reset_state() {

			global $ld_qs_api_vars;
			/**
			 * Reset the state only if we have some data in memory upfront
			 * because embed will be called only when there is valid data
			 * available in memory.
			 */
			if ( ! empty( $this->stat_refs ) ) {
				// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
				$GLOBALS['ld_qs_api_vars'] = $ld_qs_api_vars ? $ld_qs_api_vars : array();

				$object_vars = get_object_vars( $this );

				// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
				$GLOBALS['ld_qs_api_vars'][] = $object_vars;

				foreach ( $object_vars as $property => $var ) {

					switch ( gettype( $var ) ) {

						case 'integer':
							$this->$property = 0;
							break;
						case 'string':
							$this->$property = '';
							break;
						case 'array':
							$this->$property = array();
							break;
						default:
							$this->$property = null;
					}
				}
			}
		}

		/**
		 * Restore the previously stored state of an object from
		 * global variable.
		 *
		 * @since 3.3.0
		 */
		private function restore_state() {
			global $ld_qs_api_vars;

			if ( is_array( $ld_qs_api_vars ) && count( $ld_qs_api_vars ) ) {
				$recent_state = array_pop( $ld_qs_api_vars );

				foreach ( $recent_state as $property => $val ) {
					$this->$property = $val;
				}
			}
		}

		/**
		 * Retrieves the query params for the posts collection.
		 *
		 * @since 3.3.0
		 *
		 * @return array Collection parameters.
		 */
		public function get_collection_params_statistics() {
			$query_params = parent::get_collection_params();

			if ( isset( $query_params['search'] ) ) {
				unset( $query_params['search'] );
			}

			$query_params['order'] = array(
				'description' => __( 'Order sort attribute ascending or descending.', 'learndash' ),
				'type'        => 'string',
				'default'     => 'desc',
				'enum'        => array( 'asc', 'desc' ),
			);

			$query_params['orderby'] = array(
				'description' => __( 'Sort collection by object attribute.', 'learndash' ),
				'type'        => 'string',
				'default'     => 'date',
				'enum'        => array(
					'date',
					'id',
					'quiz',
					'user',
				),
			);

			if ( ! isset( $query_params['quiz'] ) ) {
				$query_params['quiz'] = array(
					'description' => sprintf(
						// translators: placeholder: Quiz.
						esc_html_x(
							'Filter by %s ID',
							'placeholder: Quiz',
							'learndash'
						),
						LearnDash_Custom_Label::get_label( 'quiz' )
					),
					'type'        => 'integer',
					'required'    => true,
					'context'     => array( 'view', 'edit' ),
				);
			}

			if ( ! isset( $query_params['user'] ) ) {
				$query_params['user'] = array(
					'description' => esc_html__( 'Filter by User ID', 'learndash' ),
					'type'        => 'integer',
					'required'    => false,
					'context'     => array( 'view', 'edit' ),
				);
			}

			$query_params['after'] = array(
				'description' => __( 'Limit response items after a given ISO8601 compliant date.', 'learndash' ),
				'type'        => 'string',
				'format'      => 'date-time',
			);

			$query_params['before'] = array(
				'description' => __( 'Limit response to items before a given ISO8601 compliant date.', 'learndash' ),
				'type'        => 'string',
				'format'      => 'date-time',
			);

			return $query_params;
		}

		/**
		 * Retrieves the query params for the posts collection.
		 *
		 * @since 3.3.0
		 *
		 * @return array Collection parameters.
		 */
		public function get_collection_params_statistics_questions() {
			$query_params = parent::get_collection_params();

			if ( isset( $query_params['search'] ) ) {
				unset( $query_params['search'] );
			}

			return $query_params;
		}

		/**
		 * Get the REST URL setting.
		 *
		 * @since 3.3.0
		 *
		 * @param string $rest_slug Settings REST slug.
		 * @param string $default_value Default value if rest_slug is not found.
		 */
		protected function get_rest_base( $rest_slug = '', $default_value = '' ) {
			$rest_base_value = null;
			if ( ! empty( $rest_slug ) ) {
				$rest_slug      .= '_' . $this->version;
				$rest_base_value = LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Section_General_REST_API', $rest_slug, $default_value );
			}

			if ( is_null( $rest_base_value ) ) {
				$rest_base_value = $default_value;
			}

			return $rest_base_value;
		}

		/**
		 * Retrieves the Stats schema, conforming to JSON Schema.
		 *
		 * @since 3.3.0
		 *
		 * @return array Item schema data.
		 */
		public function get_stats_questions_schema() {
			$schema = array(
				'$schema'    => 'http://json-schema.org/draft-04/schema#',
				'title'      => 'quiz-statistics-questions',
				'parent'     => 'quiz-statistics',
				'type'       => 'object',
				'properties' => array(
					'id'            => array(
						'description' => __( 'Unique ID for Statistics Question.', 'learndash' ),
						'type'        => 'integer',
						'context'     => array( 'view' ),
						'readonly'    => true,
					),
					'statistic'     => array(
						'description' => __( 'Statistics Ref ID.', 'learndash' ),
						'type'        => 'integer',
						'context'     => array( 'view' ),
						'readonly'    => true,
					),
					'quiz'          => array(
						'description' => sprintf(
							// translators: placeholder: Quiz.
							esc_html_x(
								'%s ID',
								'placeholder: Quiz',
								'learndash'
							),
							LearnDash_Custom_Label::get_label( 'quiz' )
						),
						'type'        => 'integer',
						'context'     => array( 'embed', 'view' ),
						'readonly'    => true,
					),
					'question'      => array(
						'description' => sprintf(
							// translators: placeholder: Question.
							esc_html_x(
								'%s ID',
								'placeholder: Question',
								'learndash'
							),
							LearnDash_Custom_Label::get_label( 'question' )
						),
						'type'        => 'integer',
						'context'     => array( 'embed', 'view' ),
						'readonly'    => true,
					),
					'question_type' => array(
						'description' => sprintf(
							// translators: placeholder: Question.
							esc_html_x(
								'%s Type',
								'placeholder: Question',
								'learndash'
							),
							LearnDash_Custom_Label::get_label( 'question' )
						),
						'type'        => 'string',
						'context'     => array( 'embed', 'view' ),
						'readonly'    => true,
					),
					'points_scored' => array(
						'description' => esc_html__( 'Points scored.', 'learndash' ),
						'type'        => 'integer',
						'context'     => array( 'view' ),
						'readonly'    => true,
					),
					'points_total'  => array(
						'description' => esc_html__( 'Points total.', 'learndash' ),
						'type'        => 'integer',
						'context'     => array( 'view' ),
						'readonly'    => true,
					),
					'answers'       => array(
						'description' => sprintf(
							// translators: placeholder: Question.
							esc_html_x(
								'The collection of %s answers.',
								'placeholder: Question',
								'learndash'
							),
							LearnDash_Custom_Label::get_label( 'question' )
						),
						'type'        => 'object',
						'context'     => array( 'view' ),
						'readonly'    => true,
					),
					'student'       => array(
						'description' => __( 'The collection of student submitted answers.', 'learndash' ),
						'type'        => 'object',
						'context'     => array( 'view' ),
						'readonly'    => true,
					),
				),
			);

			return $schema;
		}

		/**
		 * Retrieves the Stats schema, conforming to JSON Schema.
		 *
		 * @since 3.3.0
		 *
		 * @return array Item schema data.
		 */
		public function get_stats_schema() {
			$schema = array(
				'$schema'    => 'http://json-schema.org/draft-04/schema#',
				'title'      => 'quiz-statistics',
				'parent'     => 'quiz',
				'type'       => 'object',
				'properties' => array(
					'id'                => array(
						'description' => __( 'Statistics Ref ID.', 'learndash' ),
						'type'        => 'integer',
						'context'     => array( 'embed', 'view' ),
						'readonly'    => true,
					),
					'quiz'              => array(
						'description' => sprintf(
							// translators: placeholder: Quiz.
							esc_html_x(
								'%s ID.',
								'placeholder: Quiz',
								'learndash'
							),
							LearnDash_Custom_Label::get_label( 'quiz' )
						),
						'type'        => 'integer',
						'context'     => array( 'embed', 'view' ),
						'readonly'    => true,
					),
					'user'              => array(
						'description' => __( 'User ID.', 'learndash' ),
						'type'        => 'integer',
						'context'     => array( 'embed', 'view' ),
						'readonly'    => true,
					),
					'date'              => array(
						'description' => __( 'Date.', 'learndash' ),
						'type'        => array( 'string', null ),
						'format'      => 'date-time',
						'context'     => array( 'embed', 'view' ),
						'readonly'    => true,
					),
					'answers_correct'   => array(
						'description' => __( 'Answer correct.', 'learndash' ),
						'type'        => 'integer',
						'context'     => array( 'embed', 'view' ),
						'readonly'    => true,
					),
					'answers_incorrect' => array(
						'description' => __( 'Answer incorrect.', 'learndash' ),
						'type'        => 'integer',
						'context'     => array( 'embed', 'view' ),
						'readonly'    => true,
					),
				),
			);

			return $schema;
		}

		/**
		 * Checks the post_date_gmt or modified_gmt and prepare any post or
		 * modified date for single post output.
		 *
		 * @since 3.4.2
		 *
		 * @param string      $date_gmt GMT publication time.
		 * @param string|null $date     Optional. Local publication time. Default null.
		 * @return string|null ISO8601/RFC3339 formatted datetime, otherwise null.
		 */
		protected function prepare_date_response( $date_gmt, $date = null ) {
			if ( '0000-00-00 00:00:00' === $date_gmt ) {
				return null;
			}

			if ( isset( $date ) ) {
				return mysql_to_rfc3339( $date ); // phpcs:ignore PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved
			}

			return mysql_to_rfc3339( $date_gmt ); // phpcs:ignore PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved
		}

		// End of functions.
	}
}