Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 3498 lines (3066 sloc) 139.402 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 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 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/

namespace Doctrine\ODM\PHPCR;

use Doctrine\Common\Proxy\Proxy;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Util\ClassUtils;

use Doctrine\ODM\PHPCR\Exception\InvalidArgumentException;
use Doctrine\ODM\PHPCR\Exception\RuntimeException;
use Doctrine\ODM\PHPCR\Id\AssignedIdGenerator;
use Doctrine\ODM\PHPCR\Id\IdException;
use Doctrine\ODM\PHPCR\Mapping\ClassMetadata;
use Doctrine\ODM\PHPCR\Mapping\MappingException;
use Doctrine\ODM\PHPCR\Id\IdGenerator;
use Doctrine\ODM\PHPCR\Event\MoveEventArgs;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\Common\Persistence\Event\ManagerEventArgs;
use Doctrine\ODM\PHPCR\Exception\CascadeException;
use Doctrine\ODM\PHPCR\Tools\Helper\PrefetchHelper;
use Doctrine\ODM\PHPCR\Translation\MissingTranslationException;

use PHPCR\RepositoryInterface;
use PHPCR\PropertyType;
use PHPCR\NodeInterface;
use PHPCR\RepositoryException;
use PHPCR\UnsupportedRepositoryOperationException;
use PHPCR\PathNotFoundException;
use PHPCR\ItemNotFoundException;
use PHPCR\NodeType\NoSuchNodeTypeException;
use PHPCR\Util\UUIDHelper;
use PHPCR\Util\PathHelper;
use PHPCR\Util\NodeHelper;

use Jackalope\Session as JackalopeSession;

/**
* Unit of work class
*
* @license http://www.opensource.org/licenses/MIT-license.php MIT license
* @link www.doctrine-project.com
* @since 1.0
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Pascal Helfenstein <nicam@nicam.ch>
* @author Lukas Kahwe Smith <smith@pooteeweet.org>
* @author Brian King <brian@liip.ch>
* @author David Buchmann <david@liip.ch>
* @author Daniel Barsotti <daniel.barsotti@liip.ch>
*/
class UnitOfWork
{
    const STATE_NEW = 1;
    const STATE_MANAGED = 2;
    const STATE_REMOVED = 3;
    const STATE_DETACHED = 4;

    /**
* @var DocumentManager
*/
    private $dm = null;

    /**
* @var array
*/
    private $identityMap = array();

    /**
* @var array
*/
    private $documentIds = array();

    /**
* Track version history of the version documents we create, indexed by spl_object_hash
* @var \PHPCR\Version\VersionHistoryInterface[]
*/
    private $documentHistory = array();

    /**
* Track version objects of the version documents we create, indexed by spl_object_hash
* @var \PHPCR\Version\VersionInterface[]
*/
    private $documentVersion = array();

    /**
* @var array
*/
    private $documentState = array();

    /**
* Hashmap of spl_object_hash => locale => hashmap of all translated
* document fields to store fields until the flush, in case the user is
* using bindTranslation to store more than one locale in one flush.
*
* @var array
*/
    private $documentTranslations = array();

    /**
* Hashmap of spl_object_hash => { original => locale , current => locale }
* The original vs current locale is used to detect if the user changed the
* mapped locale field of a document after the last call to bindTranslation
*
* @var array
*/
    private $documentLocales = array();

    /**
* PHPCR always returns and updates the whole data of a document. If on update data is "missing"
* this means the data is deleted. This also applies to attachments. This is why we need to ensure
* that data that is not mapped is not lost. This map here saves all the "left-over" data and keeps
* track of it if necessary.
*
* @var array
*/
    private $nonMappedData = array();

    /**
* @var array
*/
    private $originalData = array();

    /**
* @var array
*/
    private $documentChangesets = array();

    /**
* List of documents that have a changed field to be updated on next flush
* oid => document
* @var array
*/
    private $scheduledUpdates = array();

    /**
* List of documents that will be inserted on next flush
* oid => document
* @var array
*/
    private $scheduledInserts = array();

    /**
* List of documents that will be moved on next flush
* oid => array(document, target path)
* @var array
*/
    private $scheduledMoves = array();

    /**
* List of parent documents that have children that will be reordered on next flush
* parent oid => list of array with records array(parent document, srcName, targetName, before) with
* - parent document the document of the child to be reordered
* - srcName the Nodename of the document to be moved,
* - targetName the Nodename of the document to move srcName to
* - before a boolean telling whether to move srcName before or after targetName
*
* @var array
*/
    private $scheduledReorders = array();

    /**
* List of documents that will be removed on next flush
* oid => document
* @var array
*/
    private $scheduledRemovals = array();

    /**
* @var array
*/
    private $visitedCollections = array();

    /**
* @var array
*/
    private $changesetComputed = array();

    /**
* @var IdGenerator
*/
    private $idGenerators = array();

    /**
* Used to generate uuid when we need to build references before flushing.
*
* @var \Closure
*/
    private $uuidGenerator;

    /**
* \PHPCR\SessionInterface
*/
    private $session;

    /**
* @var \Doctrine\Common\EventManager
*/
    private $evm;

    /**
* @var DocumentClassMapperInterface
*/
    private $documentClassMapper;

    private $prefetchHelper;

    /**
* @var boolean
*/
    private $validateDocumentName;

    /**
* @var boolean
*/
    private $writeMetadata;

    /**
* @var string
*/
    private $useFetchDepth;

    /**
* @param DocumentManager $dm
*/
    public function __construct(DocumentManager $dm)
    {
        $this->dm = $dm;
        $this->session = $dm->getPhpcrSession();
        $this->evm = $dm->getEventManager();

        $config = $dm->getConfiguration();
        $this->documentClassMapper = $config->getDocumentClassMapper();
        $this->validateDocumentName = $config->getValidateDoctrineMetadata();
        $this->writeMetadata = $config->getWriteDoctrineMetadata();
        $this->uuidGenerator = $config->getUuidGenerator();

        if ($this->session instanceof JackalopeSession) {
            $this->useFetchDepth = 'jackalope.fetch_depth';
        }
    }

    public function setPrefetchHelper($helper)
    {
        $this->prefetchHelper = $helper;
    }

    public function getPrefetchHelper()
    {
        if (!$this->prefetchHelper) {
            $this->prefetchHelper = new PrefetchHelper();
        }

        return $this->prefetchHelper;
    }

    /**
* Validate if a document is of the specified class, if the global setting
* to validate is activated.
*
* @param object $document
* @param string|null $className The class name $document must be
* instanceof. Pass empty to not validate anything.
*
* @throws PHPCRException
*/
    public function validateClassName($document, $className)
    {
        if (isset($className) && $this->validateDocumentName) {
            $this->documentClassMapper->validateClassName($this->dm, $document, $className);
        }
    }

    /**
* Get the existing document or proxy of the specified class and node data
* or create a new one if not existing.
*
* Supported hints are
* - refresh: reload the fields from the database if set
* - locale: use this locale instead of the one from the annotation or the default
* - fallback: whether to try other languages or throw a not found
* exception if the desired locale is not found. defaults to true if
* not set and locale is not given either.
* - prefetch: if set to false, do not attempt to prefetch related data.
* (This makes sense when the caller already did this beforehand.)
*
* @param null|string $className
* @param NodeInterface $node
* @param array $hints
*
* @return object
*
* @throws PHPCRExceptionInterface if $className was specified and does not match
* the class of the document corresponding to $node.
*/
    public function getOrCreateDocument($className, NodeInterface $node, array &$hints = array())
    {
        $requestedClassName = $className;
        $className = $this->documentClassMapper->getClassName($this->dm, $node, $className);
        $class = $this->dm->getClassMetadata($className);
        $id = $node->getPath();

        $document = $this->getDocumentById($id);

        if ($document) {
            if (empty($hints['refresh'])) {
                // document already loaded and no need to refresh. return early
                return $document;
            }
            $overrideLocalValuesOid = spl_object_hash($document);
        } else {
            $document = $class->newInstance();
            // delay registering the new document until children proxy have been created
            $overrideLocalValuesOid = false;
        }
        $this->validateClassName($document, $requestedClassName);

        $locale = isset($hints['locale']) ? $hints['locale'] : null;
        $fallback = isset($hints['fallback']) ? $hints['fallback'] : isset($locale);

        $documentState = array();
        $nonMappedData = array();

        // second param is false to get uuid rather than dereference reference properties to node instances
        $properties = $node->getPropertiesValues(null, false);

        foreach ($class->fieldMappings as $fieldName) {
            $mapping = $class->mappings[$fieldName];
            if (isset($properties[$mapping['property']])) {
                if (true === $mapping['multivalue']) {
                    if (isset($mapping['assoc']) && isset($properties[$mapping['assoc']])) {
                        $documentState[$fieldName] = $this->createAssoc($properties, $mapping);
                    } else {
                        $documentState[$fieldName] = (array) $properties[$mapping['property']];
                    }
                } else {
                    $documentState[$fieldName] = $properties[$mapping['property']];
                }
            } elseif (true === $mapping['multivalue']) {
                $documentState[$mapping['property']] = array();
            }
        }

        if ($class->node) {
            $documentState[$class->node] = $node;
        }

        if ($class->nodename) {
            $documentState[$class->nodename] = $node->getName();
        }

        if ($class->identifier) {
            $documentState[$class->identifier] = $node->getPath();
        }

        if (! isset($hints['prefetch']) || $hints['prefetch']) {
            $this->getPrefetchHelper()->prefetchReferences($class, $node);
        }

        // initialize inverse side collections
        foreach ($class->referenceMappings as $fieldName) {
            $mapping = $class->mappings[$fieldName];
            if ($mapping['type'] === ClassMetadata::MANY_TO_ONE) {
                if (!$node->hasProperty($mapping['property'])) {
                    continue;
                }

                try {
                    $referencedNode = $node->getProperty($mapping['property'])->getNode();
                    $proxy = $this->getOrCreateProxyFromNode($referencedNode, $locale);
                    if (isset($mapping['targetDocument']) && !$proxy instanceof $mapping['targetDocument']) {
                        throw new PHPCRException("Unexpected class for referenced document at '{$referencedNode->getPath()}'. Expected '{$mapping['targetDocument']}' but got '".ClassUtils::getClass($proxy)."'.");
                    }
                } catch (RepositoryException $e) {
                    if ($e instanceof ItemNotFoundException || isset($hints['ignoreHardReferenceNotFound'])) {
                        // a weak reference or an old version can have lost references
                        $proxy = null;
                    } else {
                        throw new PHPCRException($e->getMessage(), 0, $e);
                    }
                }

                $documentState[$fieldName] = $proxy;
            } elseif ($mapping['type'] === ClassMetadata::MANY_TO_MANY) {
                $referencedNodes = array();
                if ($node->hasProperty($mapping['property'])) {
                    foreach ($node->getProperty($mapping['property'])->getString() as $reference) {
                        $referencedNodes[] = $reference;
                    }
                }

                $targetDocument = isset($mapping['targetDocument']) ? $mapping['targetDocument'] : null;
                $coll = new ReferenceManyCollection($this->dm, $referencedNodes, $targetDocument, $locale);
                $documentState[$fieldName] = $coll;
            }
        }

        if (! isset($hints['prefetch']) || $hints['prefetch']) {
            if ($class->translator) {
                try {
                    $prefetchLocale = $locale ?: $this->dm->getLocaleChooserStrategy()->getLocale();
                } catch (InvalidArgumentException $e) {
                    throw new InvalidArgumentException($e->getMessage() . ' but document ' . $class->name . ' is mapped with translations.');
                }
            } else {
                $prefetchLocale = null;
            }
            $this->getPrefetchHelper()->prefetchHierarchy($class, $node, $prefetchLocale);
        }

        if ($class->parentMapping && $node->getDepth() > 0) {
            // do not map parent to self if we are at root
            $documentState[$class->parentMapping] = $this->getOrCreateProxyFromNode($node->getParent(), $locale);
        }

        foreach ($class->childMappings as $fieldName) {
            $mapping = $class->mappings[$fieldName];
            $documentState[$fieldName] = $node->hasNode($mapping['nodeName'])
                ? $this->getOrCreateProxyFromNode($node->getNode($mapping['nodeName']), $locale)
                : null;
        }

        foreach ($class->childrenMappings as $fieldName) {
            $mapping = $class->mappings[$fieldName];
            $documentState[$fieldName] = new ChildrenCollection($this->dm, $document, $mapping['filter'], $mapping['fetchDepth'], $locale);
        }

        foreach ($class->referrersMappings as $fieldName) {
            $mapping = $class->mappings[$fieldName];
            // get the reference type strategy (weak or hard) on the fly, as we
            // can not do it in ClassMetadata
            $referringMeta = $this->dm->getClassMetadata($mapping['referringDocument']);
            $referringField = $referringMeta->mappings[$mapping['referencedBy']];
            $documentState[$fieldName] = new ReferrersCollection(
                $this->dm,
                $document,
                $referringField['strategy'],
                $referringField['property'],
                $locale,
                $mapping['referringDocument']
            );
        }
        foreach ($class->mixedReferrersMappings as $fieldName) {
            $mapping = $class->mappings[$fieldName];
            $documentState[$fieldName] = new ImmutableReferrersCollection(
                $this->dm,
                $document,
                $mapping['referenceType'],
                $locale
            );
        }

        if (! $overrideLocalValuesOid) {
            // registering the document needs to be delayed until the children proxies where created
            $overrideLocalValuesOid = $this->registerDocument($document, $id);
        }

        $this->nonMappedData[$overrideLocalValuesOid] = $nonMappedData;
        foreach ($class->reflFields as $prop => $reflFields) {
            $value = isset($documentState[$prop]) ? $documentState[$prop] : null;
            $reflFields->setValue($document, $value);
            $this->originalData[$overrideLocalValuesOid][$prop] = $value;
        }

        // Load translations
        $this->doLoadTranslation($document, $class, $locale, $fallback);

        // Invoke the postLoad lifecycle callbacks and listeners
        if (isset($class->lifecycleCallbacks[Event::postLoad])) {
            $class->invokeLifecycleCallbacks(Event::postLoad, $document);
        }
        if ($this->evm->hasListeners(Event::postLoad)) {
            $this->evm->dispatchEvent(Event::postLoad, new LifecycleEventArgs($document, $this->dm));
        }

        return $document;
    }

    /**
* Get the existing document or proxy or create a new one for this PHPCR Node
*
* @param NodeInterface $node
* @param string $locale
*
* @return object
*/
    public function getOrCreateProxyFromNode(NodeInterface $node, $locale = null)
    {
        $targetId = $node->getPath();
        $className = $this->documentClassMapper->getClassName($this->dm, $node);

        return $this->getOrCreateProxy($targetId, $className, $locale);
    }

    /**
* Get the existing document or proxy for this id of this class, or create
* a new one.
*
* @param string $targetId
* @param string $className
* @param string $locale
*
* @return object
*/
    public function getOrCreateProxy($targetId, $className, $locale = null)
    {
        $document = $this->getDocumentById($targetId);

        // check if referenced document already exists
        if ($document) {
            $metadata = $this->dm->getClassMetadata($className);
            if ($locale && $locale !== $this->getCurrentLocale($document, $metadata)) {
                $this->doLoadTranslation($document, $metadata, $locale, true);
            }

            return $document;
        }

        $metadata = $this->dm->getClassMetadata($className);
        $proxyDocument = $this->dm->getProxyFactory()->getProxy($className, array($metadata->identifier => $targetId));

        // register the document under its own id
        $this->registerDocument($proxyDocument, $targetId);

        if ($locale) {
            $this->setLocale($proxyDocument, $this->dm->getClassMetadata($className), $locale);
        }

        return $proxyDocument;
    }

    /**
* Populate the proxy with actual data
*
* @param string $className
* @param Proxy $document
*/
    public function refreshDocumentForProxy($className, Proxy $document)
    {
        $node = $this->session->getNode($this->determineDocumentId($document));

        $hints = array('refresh' => true, 'fallback' => true);

        $oid = spl_object_hash($document);
        if (isset($this->documentLocales[$oid]['current'])) {
            $hints['locale'] = $this->documentLocales[$oid]['current'];
        }

        $this->getOrCreateDocument($className, $node, $hints);
    }

    /**
* Bind the translatable fields of the document in the specified locale.
*
* This method will update the field mapped to Locale if it does not match the $locale argument.
*
* @param object $document the document to persist a translation of
* @param string $locale the locale this document currently has
*
* @throws PHPCRException if the document is not translatable
*/
    public function bindTranslation($document, $locale)
    {
        $state = $this->getDocumentState($document);
        if ($state !== self::STATE_MANAGED) {
            throw new InvalidArgumentException('Document has to be managed to be able to bind a translation '.self::objToStr($document, $this->dm));
        }

        $class = $this->dm->getClassMetadata(get_class($document));
        if (!$this->isDocumentTranslatable($class)) {
            throw new PHPCRException('This document is not translatable, do not use bindTranslation: '.self::objToStr($document, $this->dm));
        }

        if ($this->getCurrentLocale($document) != $locale
            && false !== array_search($locale, $this->getLocalesFor($document))
        ) {
            throw new RuntimeException(sprintf(
                'Translation "%s" already exists for "%s". First load this translation if you want to change it, or remove the existing translation.',
                $locale,
                self::objToStr($document, $this->dm)
            ));
        }

        $this->setLocale($document, $class, $locale);

        $oid = spl_object_hash($document);

        if (empty($this->documentTranslations[$oid])) {
            $this->documentTranslations[$oid] = array();
        }

        foreach ($class->translatableFields as $field) {
            $this->documentTranslations[$oid][$locale][$field] = $class->reflFields[$field]->getValue($document);
        }
    }

    /**
* Schedule insertion of this document and cascade if necessary.
*
* @param object $document
*/
    public function scheduleInsert($document)
    {
        $visited = array();
        $this->doScheduleInsert($document, $visited);
    }

    private function doScheduleInsert($document, &$visited, $overrideIdGenerator = null)
    {
        if (!is_object($document)) {
            throw new PHPCRException(sprintf(
                'Expected a mapped object, found <%s>',
                gettype($document)
            ));
        }

        $oid = spl_object_hash($document);
        // To avoid recursion loops (over children and parents)
        if (isset($visited[$oid])) {
            return;
        }
        $visited[$oid] = true;

        $class = $this->dm->getClassMetadata(get_class($document));
        if ($class->isMappedSuperclass) {
            throw new InvalidArgumentException('Cannot persist a mapped super class instance: '.$class->name);
        }

        $this->cascadeScheduleParentInsert($class, $document, $visited);

        $state = $this->getDocumentState($document);
        switch ($state) {
            case self::STATE_NEW:
                $this->persistNew($class, $document, $overrideIdGenerator);
                break;
            case self::STATE_MANAGED:
                // TODO: Change Tracking Deferred Explicit
                break;
            case self::STATE_REMOVED:
                unset($this->scheduledRemovals[$oid]);
                $this->setDocumentState($oid, self::STATE_MANAGED);
                break;
            case self::STATE_DETACHED:
                throw new InvalidArgumentException('Detached document or new document with already existing id passed to persist(): '.self::objToStr($document, $this->dm));
        }

        $this->cascadeScheduleInsert($class, $document, $visited);
    }

    /**
*
* @param ClassMetadata $class
* @param object $document
* @param array $visited
*/
    private function cascadeScheduleInsert($class, $document, &$visited)
    {
        foreach (array_merge($class->referenceMappings, $class->referrersMappings) as $fieldName) {
            $mapping = $class->mappings[$fieldName];
            if (!($mapping['cascade'] & ClassMetadata::CASCADE_PERSIST)) {
                continue;
            }

            $related = $class->reflFields[$fieldName]->getValue($document);
            if ($related !== null) {
                if (ClassMetadata::MANY_TO_ONE === $mapping['type']) {
                    if (is_array($related) || $related instanceof Collection) {
                        throw new PHPCRException(sprintf(
                            'Referenced document is not stored correctly in a reference-one property. Do not use array notation or a (ReferenceMany)Collection in field "%s" of document "%s"',
                            $fieldName,
                            self::objToStr($document, $this->dm)
                        ));
                    }
                    if (!is_object($related)) {
                        throw new PHPCRException(sprintf(
                            'A reference field may only contain mapped documents, found <%s> in field "%s" of "%s"',
                            gettype($related),
                            $fieldName,
                            self::objToStr($document, $this->dm)
                        ));
                    }

                    if ($this->getDocumentState($related) === self::STATE_NEW) {
                        $this->doScheduleInsert($related, $visited);
                    }
                } else {
                    if (!is_array($related) && !$related instanceof Collection) {
                        throw new PHPCRException('Referenced documents are not stored correctly in a reference-many property. Use array notation or a (ReferenceMany)Collection: '.self::objToStr($document, $this->dm));
                    }
                    foreach ($related as $relatedDocument) {
                        if (!isset($relatedDocument)) {
                            continue;
                        }
                        if (!is_object($relatedDocument)) {
                            throw new PHPCRException(sprintf(
                                'A reference field may only contain mapped documents, found <%s> in field "%s" of "%s"',
                                gettype($relatedDocument),
                                $fieldName,
                                self::objToStr($document, $this->dm)
                            ));
                        }
                        if ($this->getDocumentState($relatedDocument) === self::STATE_NEW) {
                            $this->doScheduleInsert($relatedDocument, $visited);
                        }
                    }
                }
            }
        }
    }

    private function cascadeScheduleParentInsert($class, $document, &$visited)
    {
        if ($class->parentMapping) {
            $parent = $class->reflFields[$class->parentMapping]->getValue($document);
            if ($parent !== null && $this->getDocumentState($parent) === self::STATE_NEW) {
                if (!is_object($parent)) {
                    throw new PHPCRException(sprintf(
                        'A parent field may only contain mapped documents, found <%s> in field "%s" of "%s"',
                        gettype($parent),
                        $class->parentMapping,
                        self::objToStr($document, $this->dm)
                    ));
                 }

                $this->doScheduleInsert($parent, $visited);
            }
        }
    }

    /**
* @param string $type the id generator type
*
* @return IdGenerator
*/
    private function getIdGenerator($type)
    {
        if (!isset($this->idGenerators[$type])) {
            $this->idGenerators[$type] = IdGenerator::create($type);
        }

        return $this->idGenerators[$type];
    }

    public function scheduleMove($document, $targetPath)
    {
        $oid = spl_object_hash($document);

        $state = $this->getDocumentState($document);

        switch ($state) {
            case self::STATE_NEW:
                unset($this->scheduledInserts[$oid]);
                break;
            case self::STATE_REMOVED:
                unset($this->scheduledRemovals[$oid]);
                break;
            case self::STATE_DETACHED:
                throw new InvalidArgumentException('Detached document passed to move(): '.self::objToStr($document, $this->dm));
        }

        $this->scheduledMoves[$oid] = array($document, $targetPath);
        $this->setDocumentState($oid, self::STATE_MANAGED);
    }

    public function scheduleReorder($document, $srcName, $targetName, $before)
    {
        $oid = spl_object_hash($document);

        $state = $this->getDocumentState($document);
        switch ($state) {
            case self::STATE_REMOVED:
                throw new InvalidArgumentException('Removed document passed to reorder(): '.self::objToStr($document, $this->dm));
            case self::STATE_DETACHED:
                throw new InvalidArgumentException('Detached document passed to reorder(): '.self::objToStr($document, $this->dm));
        }

        if (! isset($this->scheduledReorders[$oid])) {
            $this->scheduledReorders[$oid] = array();
        }
        $this->scheduledReorders[$oid][] = array($document, $srcName, $targetName, $before);
    }

    public function scheduleRemove($document)
    {
        $visited = array();
        $this->doRemove($document, $visited);
    }

    private function doRemove($document, &$visited)
    {
        $oid = spl_object_hash($document);
        if (isset($visited[$oid])) {
            return;
        }
        $visited[$oid] = true;

        $state = $this->getDocumentState($document);
        switch ($state) {
            case self::STATE_NEW:
                unset($this->scheduledInserts[$oid]);
                break;
            case self::STATE_MANAGED:
                unset($this->scheduledMoves[$oid]);
                unset($this->scheduledReorders[$oid]);
                break;
            case self::STATE_DETACHED:
                throw new InvalidArgumentException('Detached document passed to remove(): '.self::objToStr($document, $this->dm));
        }

        $this->scheduledRemovals[$oid] = $document;
        $this->setDocumentState($oid, self::STATE_REMOVED);

        $class = $this->dm->getClassMetadata(get_class($document));
        if (isset($class->lifecycleCallbacks[Event::preRemove])) {
            $class->invokeLifecycleCallbacks(Event::preRemove, $document);
        }
        if ($this->evm->hasListeners(Event::preRemove)) {
            $this->evm->dispatchEvent(Event::preRemove, new LifecycleEventArgs($document, $this->dm));
        }

        $this->cascadeRemove($class, $document, $visited);
    }

    private function cascadeRemove(ClassMetadata $class, $document, &$visited)
    {
        foreach (array_merge($class->referenceMappings, $class->referrersMappings) as $fieldName) {
            $mapping = $class->mappings[$fieldName];
            if (!($mapping['cascade'] & ClassMetadata::CASCADE_REMOVE)) {
                continue;
            }

            $related = $class->reflFields[$fieldName]->getValue($document);
            if ($related instanceof Collection || is_array($related)) {
                // If its a PersistentCollection initialization is intended! No unwrap!
                foreach ($related as $relatedDocument) {
                    $this->doRemove($relatedDocument, $visited);
                }
            } elseif ($related !== null) {
                $this->doRemove($related, $visited);
            }
        }

        // remove is cascaded to children automatically on PHPCR level
    }

    /**
* recurse over all known child documents to remove them form this unit of work
* as their parent gets removed from phpcr. If you do not, flush will try to create
* orphaned nodes if these documents are modified which leads to a PHPCR exception
*
* @param object $document
*/
    private function purgeChildren($document)
    {
        if ($document instanceof Proxy && !$document->__isInitialized()) {
            return;
        }

        $class = $this->dm->getClassMetadata(get_class($document));
        foreach ($class->childMappings as $fieldName) {
            $child = $class->reflFields[$fieldName]->getValue($document);
            if ($child !== null) {
                $this->purgeChildren($child);
                $this->unregisterDocument($child);
            }
        }
    }

    /**
* @param object|string $document document instance or document object hash
* @param int $state
*/
    private function setDocumentState($document, $state)
    {
        $oid = is_object($document) ? spl_object_hash($document) : $document;
        $this->documentState[$oid] = $state;
    }

    /**
* Get the state of this document
*
* STATE_NEW: the document is not persisted, but a valid mapped document
* STATE_MANAGED: the document is tracked and will be updated on flush
* STATE_REMOVED: the document is scheduled for removal
* STATE_DETACHED: there is a corresponding Node in storage, but this document is not bound to it
*
* @param object $document the document to get the state of
*
* @return int one of the STATE_* constants of this class
*/
    public function getDocumentState($document)
    {
        $oid = spl_object_hash($document);
        if (!isset($this->documentState[$oid])) {
            // this will only use the metadata if id is mapped
            $id = $this->determineDocumentId($document);

            if (!$id) {
                return self::STATE_NEW;
            }

            if ($this->getDocumentById($id)) {
                return self::STATE_DETACHED;
            }

            return $this->dm->getPhpcrSession()->nodeExists($id)
                ? self::STATE_DETACHED : self::STATE_NEW;
        }

        return $this->documentState[$oid];
    }

    /**
* Checks whether a document is scheduled for insertion.
*
* @param object $document
*
* @return boolean
*/
    public function isScheduledForInsert($document)
    {
        return isset($this->scheduledInserts[spl_object_hash($document)]);
    }

    /**
* Detects the changes for a single document
*
* @param object $document
*/
    public function computeSingleDocumentChangeSet($document)
    {
        $state = $this->getDocumentState($document);
        if ($state !== self::STATE_MANAGED) {
            throw new InvalidArgumentException('Document has to be managed for single computation '.self::objToStr($document, $this->dm));
        }

        foreach ($this->scheduledInserts as $insertedDocument) {
            $class = $this->dm->getClassMetadata(get_class($insertedDocument));
            $this->computeChangeSet($class, $insertedDocument);
        }

        // Ignore uninitialized proxy objects
        if ($document instanceof Proxy && !$document->__isInitialized()) {
            return;
        }

        $oid = spl_object_hash($document);
        if (!isset($this->scheduledInserts[$oid])) {
            $class = $this->dm->getClassMetadata(get_class($document));
            $this->computeChangeSet($class, $document);
        }
    }

    /**
* Detects the changes that need to be persisted
*/
    public function computeChangeSets()
    {
        foreach ($this->identityMap as $document) {
            $state = $this->getDocumentState($document);
            if ($state === self::STATE_MANAGED) {
                $class = $this->dm->getClassMetadata(get_class($document));
                $this->computeChangeSet($class, $document);
            }
        }
    }

    /**
* Get a documents actual data, flattening all the objects to arrays.
*
* @param ClassMetadata $class
* @param object $document
*
* @return array
*/
    private function getDocumentActualData(ClassMetadata $class, $document)
    {
        $actualData = array();
        foreach ($class->reflFields as $fieldName => $reflProperty) {
            // do not set the version info fields if they have values, they are not to be managed by the user in write scenarios.
            if ($fieldName === $class->versionNameField
                || $fieldName === $class->versionCreatedField
            ) {
                continue;
            }
            $value = $reflProperty->getValue($document);
            $actualData[$fieldName] = $value;
        }

        return $actualData;
    }

    /**
* Determine the nodename of a child in a children list.
*
* @param string $parentId Id of the parent document
* @param string $nodename Name to use if we can't determine the node name otherwise.
* @param object $child The child document
* @param object $parent The parent document
*
* @return mixed|string
*
* @throws PHPCRException
*/
    private function getChildNodename($parentId, $nodename, $child, $parent)
    {
        $childClass = $this->dm->getClassMetadata(get_class($child));
        if ($childClass->nodename && $childClass->reflFields[$childClass->nodename]->getValue($child)) {
            $nodename = $childClass->reflFields[$childClass->nodename]->getValue($child);

            if ($exception = $childClass->isValidNodename($nodename)) {
                throw IdException::illegalName($child, $childClass->nodename, $nodename);
            }
        } else {
            $childId = '';
            if ($childClass->identifier) {
                $childId = $childClass->getIdentifierValue($child);
            }
            if (!$childId) {
                $generator = $this->getIdGenerator($childClass->idGenerator);
                $childId = $generator->generate($child, $childClass, $this->dm, $parent);
            }

            if ('' !== $childId) {
                if ($childId !== $parentId.'/'.PathHelper::getNodeName($childId)) {
                    throw PHPCRException::cannotMoveByAssignment(self::objToStr($child, $this->dm));
                }
                $nodename = PathHelper::getNodeName($childId);
            }
        }

        return $nodename;
    }

    private function computeAssociationChanges($class, $oid, $isNew, $actualData, $assocType)
    {
        switch ($assocType) {
            case 'reference':
                $mappings = $class->referenceMappings;
                $computeMethod = 'computeReferenceChanges';
                break;
            case 'referrer':
                $mappings = $class->referrersMappings;
                $computeMethod = 'computeReferrerChanges';
                break;
            default:
                throw new InvalidArgumentException('Unsupported association type used: '.$assocType);
        }

        foreach ($mappings as $fieldName) {
            if ($actualData[$fieldName]) {
                if (is_array($actualData[$fieldName]) || $actualData[$fieldName] instanceof Collection) {
                    if ($actualData[$fieldName] instanceof PersistentCollection) {
                        if (!$actualData[$fieldName]->isInitialized()) {
                            continue;
                        }

                        $coid = spl_object_hash($actualData[$fieldName]);
                        $this->visitedCollections[$coid] = $actualData[$fieldName];
                    }

                    $mapping = $class->mappings[$fieldName];
                    foreach ($actualData[$fieldName] as $association) {
                        if ($association !== null) {
                            $this->$computeMethod($mapping, $association);
                        }
                    }

                    if (!$isNew && $mapping['cascade'] & ClassMetadata::CASCADE_REMOVE
                        && (is_array($this->originalData[$oid][$fieldName])
                            || $this->originalData[$oid][$fieldName] instanceof Collection
                        )
                    ) {
                        $associations = $this->originalData[$oid][$fieldName]->getOriginalPaths();
                        foreach ($associations as $association) {
                            $association = $this->getDocumentById($association);
                            if ($association && !$this->originalData[$oid][$fieldName]->contains($association)) {
                                $this->scheduleRemove($association);
                            }
                        }
                    }
                } elseif ('reference' === $assocType && $actualData[$fieldName]) {
                    $mapping = $class->mappings[$fieldName];
                    $this->computeReferenceChanges($mapping, $actualData[$fieldName]);
                }
            }
        }
    }

    /**
* Computes changeset for a given document.
*
* @param ClassMetadata $class
* @param object $document
*/
    public function computeChangeSet(ClassMetadata $class, $document)
    {
        if ($document instanceof Proxy && !$document->__isInitialized()) {
            return;
        }

        $oid = spl_object_hash($document);
        if (in_array($oid, $this->changesetComputed)) {
            return;
        }

        $this->changesetComputed[] = $oid;

        $actualData = $this->getDocumentActualData($class, $document);
        $id = $this->getDocumentId($document, false);

        $isNew = !isset($this->originalData[$oid]);
        if ($isNew) {
            // Document is New and should be inserted
            $this->originalData[$oid] = $actualData;
            $this->documentChangesets[$oid] = array('fields' => $actualData, 'reorderings' => array());
            $this->scheduledInserts[$oid] = $document;
        }

        if ($class->parentMapping && isset($actualData[$class->parentMapping])) {
            $parent = $actualData[$class->parentMapping];
            $parentClass = $this->dm->getClassMetadata(get_class($parent));
            $state = $this->getDocumentState($parent);

            if ($state === self::STATE_MANAGED) {
                $this->computeChangeSet($parentClass, $parent);
            }
        }

        foreach ($class->childMappings as $fieldName) {
            if ($actualData[$fieldName]) {
                if (is_array($actualData[$fieldName]) || $actualData[$fieldName] instanceof Collection) {
                    throw PHPCRException::childFieldIsArray(
                        self::objToStr($document, $this->dm),
                        $fieldName
                    );
                }
                if (!is_object($actualData[$fieldName])) {
                    throw PHPCRException::childFieldNoObject(
                        self::objToStr($document, $this->dm),
                        $fieldName,
                        gettype($actualData[$fieldName])
                    );
                }

                $mapping = $class->mappings[$fieldName];
                $actualData[$fieldName] = $this->computeChildChanges($mapping, $actualData[$fieldName], $id, $mapping['nodeName']);
            }
        }

        $this->computeAssociationChanges($class, $oid, $isNew, $actualData, 'reference');
        $this->computeAssociationChanges($class, $oid, $isNew, $actualData, 'referrer');

        foreach ($class->mixedReferrersMappings as $fieldName) {
            if ($actualData[$fieldName]
                && $actualData[$fieldName] instanceof PersistentCollection
                && $actualData[$fieldName]->isDirty()
            ) {
                throw new PHPCRException("The immutable mixed referrer collection in field $fieldName is dirty");
            }
        }

        if ($isNew) {
            // much simpler handling for children
            foreach ($class->childrenMappings as $fieldName) {
                if ($actualData[$fieldName]) {
                    if (!is_array($actualData[$fieldName]) && !$actualData[$fieldName] instanceof Collection) {
                        throw PHPCRException::childrenFieldNoArray(
                            self::objToStr($document, $this->dm),
                            $fieldName
                        );
                    }

                    $mapping = $class->mappings[$fieldName];
                    foreach ($actualData[$fieldName] as $originalNodename => $child) {
                        if (!is_object($child)) {
                            throw PHPCRException::childrenContainsNonObject(
                                self::objToStr($document, $this->dm),
                                $fieldName,
                                gettype($child)
                            );
                        }

                        $nodename = $this->getChildNodename($id, $originalNodename, $child, $document);
                        $actualData[$fieldName][$nodename] = $this->computeChildChanges($mapping, $child, $id, $nodename, $document);
                        if (0 !== strcmp($originalNodename, $nodename)) {
                            unset($actualData[$fieldName][$originalNodename]);
                        }
                        $childNames[] = $nodename;
                    }
                }
            }
        } else {
            // collect assignment move operations
            $destPath = $destName = false;

            if (isset($this->originalData[$oid][$class->parentMapping])
                && isset($actualData[$class->parentMapping])
                && $this->originalData[$oid][$class->parentMapping] !== $actualData[$class->parentMapping]
            ) {
                $destPath = $this->getDocumentId($actualData[$class->parentMapping]);
            }

            if (isset($this->originalData[$oid][$class->nodename])
                && isset($actualData[$class->nodename])
                && $this->originalData[$oid][$class->nodename] !== $actualData[$class->nodename]
            ) {
                $destName = $actualData[$class->nodename];
            }

            // there was assignment move
            if ($destPath || $destName) {
                // add the other field if only one was changed
                if (false === $destPath) {
                    $destPath = isset($actualData[$class->parentMapping])
                        ? $this->getDocumentId($actualData[$class->parentMapping])
                        : PathHelper::getParentPath($this->getDocumentId($document));
                }
                if (false === $destName) {
                    $destName = $actualData[$class->nodename]
                        ? $actualData[$class->nodename]
                        : PathHelper::getNodeName($this->getDocumentId($document));
                }

                // make sure destination nodename is okay
                if ($exception = $class->isValidNodename($destName)) {
                    throw IdException::illegalName($document, $class->nodename, $destName);
                }

                // prevent path from becoming "//foobar" when moving to root node.
                $targetPath = ('/' == $destPath) ? "/$destName" : "$destPath/$destName";

                $this->scheduleMove($document, $targetPath);
            }

            if (isset($this->originalData[$oid][$class->identifier])
                && isset($actualData[$class->identifier])
                && $this->originalData[$oid][$class->identifier] !== $actualData[$class->identifier]
            ) {
                throw new PHPCRException('The Id is immutable ('.$this->originalData[$oid][$class->identifier].' !== '.$actualData[$class->identifier].'). Please use DocumentManager::move to move the document: '.self::objToStr($document, $this->dm));
            }

            foreach ($class->childrenMappings as $fieldName) {
                if ($actualData[$fieldName] instanceof PersistentCollection) {
                    if (!$actualData[$fieldName]->isInitialized()) {
                        continue;
                    }

                    $coid = spl_object_hash($actualData[$fieldName]);
                    $this->visitedCollections[$coid] = $actualData[$fieldName];
                }

                $mapping = $class->mappings[$fieldName];

                $childNames = array();
                $movedChildNames = array();
                if ($actualData[$fieldName]) {
                    if (!is_array($actualData[$fieldName]) && !$actualData[$fieldName] instanceof Collection) {
                        throw PHPCRException::childrenFieldNoArray(
                            self::objToStr($document, $this->dm),
                            $fieldName
                        );
                    }

                    foreach ($actualData[$fieldName] as $originalNodename => $child) {
                        if (!is_object($child)) {
                            throw PHPCRException::childrenContainsNonObject(
                                self::objToStr($document, $this->dm),
                                $fieldName,
                                gettype($child)
                            );
                        }

                        $nodename = $this->getChildNodename($id, $originalNodename, $child, $document);
                        $actualData[$fieldName][$nodename] = $this->computeChildChanges($mapping, $child, $id, $nodename, $document);
                        if (0 !== strcmp($originalNodename, $nodename)) {
                            unset($actualData[$fieldName][$originalNodename]);
                            $movedChildNames[] = (string) $originalNodename;
                        }
                        $childNames[] = $nodename;
                    }
                }

                if ($this->originalData[$oid][$fieldName] instanceof ChildrenCollection) {
                    $this->originalData[$oid][$fieldName]->initialize();
                    $originalNames = $this->originalData[$oid][$fieldName]->getOriginalNodenames();
                    foreach ($originalNames as $key => $childName) {
                        // check moved children to not accidentally remove a child that simply moved away.
                        if (!(in_array($childName, $childNames) || in_array($childName, $movedChildNames))) {
                            $child = $this->getDocumentById($id.'/'.$childName);
                            $this->scheduleRemove($child);
                            unset($originalNames[$key]);
                        }
                    }
                }

                if (!empty($childNames) && isset($originalNames)) {
                    // reindex the arrays to avoid holes in the indexes
                    $originalNames = array_values($originalNames);
                    $originalNames = array_merge($originalNames, array_diff($childNames, $originalNames));
                    if ($originalNames !== $childNames) {

                        $reordering = NodeHelper::calculateOrderBefore($originalNames, $childNames);

                        if (empty($this->documentChangesets[$oid])) {
                            $this->documentChangesets[$oid] = array('fields' => array(), 'reorderings' => array($reordering));
                        } else {
                            $this->documentChangesets[$oid]['reorderings'][] = $reordering;
                        }

                        $this->scheduledUpdates[$oid] = $document;
                    } elseif (isset($this->documentChangesets[$oid])) {
                        // make sure we don't keep an old changeset if an event changed
                        // the document and no reoderings changeset remain.
                        $this->documentChangesets[$oid]['reorderings'] = array();
                    }
                }
            }

            if (!isset($this->documentLocales[$oid])
                || $this->documentLocales[$oid]['current'] === $this->documentLocales[$oid]['original']
            ) {
                // remove anything from $actualData that did not change
                foreach ($actualData as $fieldName => $fieldValue) {
                    if (isset($class->mappings[$fieldName])) {
                        if ($this->originalData[$oid][$fieldName] !== $fieldValue) {
                            continue;
                        }
                        if (($fieldValue instanceof ReferenceManyCollection
                                || $fieldValue instanceof ReferrersCollection
                            )
                            && $fieldValue->changed()
                        ) {
                            continue;
                        }
                    }

                    unset($actualData[$fieldName]);
                }
            }

            if (count($actualData)) {
                if (empty($this->documentChangesets[$oid])) {
                    $this->documentChangesets[$oid] = array('fields' => $actualData, 'reorderings' => array());
                } else {
                    $this->documentChangesets[$oid]['fields'] = $actualData;
                }

                $this->scheduledUpdates[$oid] = $document;
            } elseif (isset($this->documentChangesets[$oid])) {
                // make sure we don't keep an old changeset if an event changed
                // the document and no field changeset remains.
                $this->documentChangesets[$oid]['fields'] = array();
            }
        }
    }

    /**
* Computes the changes of a child.
*
* @param array $mapping the mapping data
* @param mixed $child the child document.
* @param string $parentId the id of the parent document
* @param string $nodename the name of the node as specified by the mapping
* @param mixed $parent the parent document
*
* @return object the child instance (if we are replacing a child this can be a different instance than was originally provided)
*/
    private function computeChildChanges($mapping, $child, $parentId, $nodename, $parent = null)
    {
        $targetClass = $this->dm->getClassMetadata(get_class($child));
        $state = $this->getDocumentState($child);

        switch ($state) {
            case self::STATE_NEW:
                // cascade persist is implicit on children, no check for cascading

                // check if we have conflicting nodename information on creation.
                if ($targetClass->nodename) {
                    $assignedName = $targetClass->getFieldValue($child, $targetClass->nodename);
                    if ($assignedName && $assignedName != $nodename) {
                        throw IdException::conflictingChildName(
                            $parentId,
                            $mapping['fieldName'],
                            $nodename,
                            $child,
                            $assignedName
                        );
                    }
                }
                $childId = $parentId.'/'.$nodename;
                $targetClass->setIdentifierValue($child, $childId);

                if ($this->getDocumentById($childId)) {
                    $child = $this->merge($child);
                } else {
                    $this->persistNew($targetClass, $child, ClassMetadata::GENERATOR_TYPE_ASSIGNED, $parent);
                }

                $this->computeChangeSet($targetClass, $child);
                break;
            case self::STATE_DETACHED:
                throw new InvalidArgumentException('A detached document was found through a child relationship during cascading a persist operation: '.self::objToStr($child, $this->dm));
            default:
                if (PathHelper::getParentPath($this->getDocumentId($child)) !== $parentId) {
                    throw PHPCRException::cannotMoveByAssignment(self::objToStr($child, $this->dm));
                }
        }

        return $child;
    }

    /**
* Computes the changes of a reference.
*
* @param array $mapping the mapping data
* @param mixed $reference the referenced document.
*/
    private function computeReferenceChanges($mapping, $reference)
    {
        $targetClass = $this->dm->getClassMetadata(get_class($reference));
        $state = $this->getDocumentState($reference);

        switch ($state) {
            case self::STATE_NEW:
                if (!($mapping['cascade'] & ClassMetadata::CASCADE_PERSIST) ) {
                    throw CascadeException::newDocumentFound(self::objToStr($reference));
                }
                $this->persistNew($targetClass, $reference);
                $this->computeChangeSet($targetClass, $reference);
                break;
            case self::STATE_DETACHED:
                throw new InvalidArgumentException('A detached document was found through a reference during cascading a persist operation: '.self::objToStr($reference, $this->dm));
        }
    }

    /**
* Computes the changes of a referrer.
*
* @param array $mapping the mapping data
* @param mixed $referrer the referenced document.
*/
    private function computeReferrerChanges($mapping, $referrer)
    {
        $targetClass = $this->dm->getClassMetadata(get_class($referrer));
        $state = $this->getDocumentState($referrer);

        switch ($state) {
            case self::STATE_NEW:
                if (!($mapping['cascade'] & ClassMetadata::CASCADE_PERSIST) ) {
                    throw CascadeException::newDocumentFound(self::objToStr($referrer));
                }
                $this->persistNew($targetClass, $referrer);
                $this->computeChangeSet($targetClass, $referrer);
                break;
            case self::STATE_DETACHED:
                throw new InvalidArgumentException('A detached document was found through a referrer during cascading a persist operation: '.self::objToStr($referrer, $this->dm));
        }
    }

    /**
* Persist new document, marking it managed and generating the id and the node.
*
* This method is either called through `DocumentManager#persist()` or during `DocumentManager#flush()`,
* when persistence by reachability is applied.
*
* @param ClassMetadata $class
* @param object $document
*/
    public function persistNew(ClassMetadata $class, $document, $overrideIdGenerator = null, $parent = null)
    {
        if (isset($class->lifecycleCallbacks[Event::prePersist])) {
            $class->invokeLifecycleCallbacks(Event::prePersist, $document);
        }
        if ($this->evm->hasListeners(Event::prePersist)) {
            $this->evm->dispatchEvent(Event::prePersist, new LifecycleEventArgs($document, $this->dm));
        }

        $generator = $this->getIdGenerator($overrideIdGenerator ? $overrideIdGenerator : $class->idGenerator);
        $id = $generator->generate($document, $class, $this->dm, $parent);
        $this->registerDocument($document, $id);

        if (!$generator instanceof AssignedIdGenerator) {
            $class->setIdentifierValue($document, $id);
        }

        // If the UUID is mapped, generate it early resp. validate if already present.
        $uuidFieldName = $class->getUuidFieldName();
        if ($uuidFieldName) {
            $existingUuid = $class->getFieldValue($document, $uuidFieldName);
            if (!$existingUuid) {
                $class->setFieldValue($document, $uuidFieldName, $this->generateUuid());
            } elseif (!UUIDHelper::isUUID($existingUuid)) {
                throw RuntimeException::invalidUuid($id, ClassUtils::getClass($document), $existingUuid);
            }
        }
    }

    public function refresh($document)
    {
        $visited = array();
        $this->doRefresh($document, $visited);
    }

    private function doRefresh($document, &$visited)
    {
        $oid = spl_object_hash($document);
        if (isset($visited[$oid])) {
            return;
        }
        $visited[$oid] = true;

        if ($this->getDocumentState($document) !== self::STATE_MANAGED) {
            throw new InvalidArgumentException('Document has to be managed to be refreshed '.self::objToStr($document, $this->dm));
        }

        $this->session->refresh(true);
        $node = $this->session->getNode($this->getDocumentId($document));

        $class = $this->dm->getClassMetadata(get_class($document));
        $this->cascadeRefresh($class, $document, $visited);

        $hints = array('refresh' => true);
        $this->getOrCreateDocument(ClassUtils::getClass($document), $node, $hints);
    }

    public function merge($document)
    {
        $visited = array();

        return $this->doMerge($document, $visited);
    }

    private function doMergeSingleDocumentProperty($managedCopy, $document, \ReflectionProperty $prop, array $mapping)
    {
        if (null === $document) {
            $prop->setValue($managedCopy, null);
        } elseif (!($mapping['cascade'] & ClassMetadata::CASCADE_MERGE)) {
            if ($this->getDocumentState($document) == self::STATE_MANAGED) {
                $prop->setValue($managedCopy, $document);
            } else {
                $targetClass = $this->dm->getClassMetadata(get_class($document));
                $id = $this->determineDocumentId($document, $targetClass);
                $proxy = $this->getOrCreateProxy($id, $targetClass->name);
                $prop->setValue($managedCopy, $proxy);
                $this->registerDocument($proxy, $id);
            }
        }
    }

    private function cascadeMergeCollection($managedCol, array $mapping)
    {
        if (!$managedCol instanceof PersistentCollection
            || !($mapping['cascade'] & ClassMetadata::CASCADE_MERGE)
        ) {
            return;
        }

        $managedCol->initialize();
        if (!$managedCol->isEmpty()) {
            // clear managed collection, in casacadeMerge() the collection is filled again.
            $managedCol->unwrap()->clear();
            $managedCol->setDirty(true);
        }
    }

    private function doMerge($document, array &$visited, $prevManagedCopy = null, $assoc = null)
    {
        $oid = spl_object_hash($document);
        if (isset($visited[$oid])) {
            return $document; // Prevent infinite recursion
        }

        $visited[$oid] = $document; // mark visited

        $class = $this->dm->getClassMetadata(get_class($document));
        $locale = $this->getCurrentLocale($document, $class);

        // First we assume DETACHED, although it can still be NEW but we can avoid
        // an extra db-roundtrip this way. If it is not MANAGED but has an identity,
        // we need to fetch it from the db anyway in order to merge.
        // MANAGED entities are ignored by the merge operation.
        if ($this->getDocumentState($document) == self::STATE_MANAGED) {
            $managedCopy = $document;
        } else {
            $id = $this->determineDocumentId($document, $class);
            $persist = false;

            if (!$id) {
                // document is new
                $managedCopy = $class->newInstance();
                $persist = true;
            } else {
                $managedCopy = $this->getDocumentById($id);
                if ($managedCopy) {
                    // We have the document in-memory already, just make sure its not removed.
                    if ($this->getDocumentState($managedCopy) == self::STATE_REMOVED) {
                        throw new InvalidArgumentException("Removed document detected during merge at '$id'. Cannot merge with a removed document.");
                    }

                    if (ClassUtils::getClass($managedCopy) != ClassUtils::getClass($document)) {
                        throw new InvalidArgumentException('Can not merge documents of different classes.');
                    }

                    if ($this->getCurrentLocale($managedCopy, $class) !== $locale) {
                        $this->doLoadTranslation($document, $class, $locale, true);
                    }
                } elseif ($locale) {
                    // We need to fetch the managed copy in order to merge.
                    $managedCopy = $this->dm->findTranslation($class->name, $id, $locale);
                } else {
                    // We need to fetch the managed copy in order to merge.
                    $managedCopy = $this->dm->find($class->name, $id);
                }

                if ($managedCopy === null) {
                    // If the identifier is ASSIGNED, it is NEW, otherwise an error
                    // since the managed document was not found.
                    if ($class->idGenerator !== ClassMetadata::GENERATOR_TYPE_ASSIGNED) {
                        throw new InvalidArgumentException("Document not found in merge operation: $id");
                    }

                    $managedCopy = $class->newInstance();
                    $class->setIdentifierValue($managedCopy, $id);
                    $persist = true;
                }
            }

            $managedOid = spl_object_hash($managedCopy);

            // Merge state of $document into existing (managed) document
            foreach ($class->reflFields as $fieldName => $prop) {
                $other = $prop->getValue($document);
                if (($other instanceof PersistentCollection && !$other->isInitialized())
                    || ($other instanceof Proxy && !$other->__isInitialized())
                ) {
                    // do not merge fields marked lazy that have not been fetched.
                    // keep the lazy persistent collection of the managed copy.
                    continue;
                }
                $mapping = $class->mappings[$fieldName];
                if (ClassMetadata::MANY_TO_ONE === $mapping['type']) {
                    $this->doMergeSingleDocumentProperty($managedCopy, $other, $prop, $mapping);
                } elseif (ClassMetadata::MANY_TO_MANY === $mapping['type']) {
                    $managedCol = $prop->getValue($managedCopy);
                    if (!$managedCol) {
                        $managedCol = new ReferenceManyCollection(
                            $this->dm,
                            array(),
                            isset($mapping['targetDocument']) ? $mapping['targetDocument'] : null,
                            $locale
                        );
                        $prop->setValue($managedCopy, $managedCol);
                        $this->originalData[$managedOid][$fieldName] = $managedCol;
                    }
                    $this->cascadeMergeCollection($managedCol, $mapping);
                } elseif ('child' === $mapping['type']) {
                    if (null !== $other) {
                        $this->doMergeSingleDocumentProperty($managedCopy, $other, $prop, $mapping);
                    }
                } elseif ('children' === $mapping['type']) {
                    $managedCol = $prop->getValue($managedCopy);
                    if (!$managedCol) {
                        $managedCol = new ChildrenCollection(
                            $this->dm,
                            $managedCopy,
                            $mapping['filter'],
                            $mapping['fetchDepth'],
                            $locale
                        );
                        $prop->setValue($managedCopy, $managedCol);
                        $this->originalData[$managedOid][$fieldName] = $managedCol;
                    }
                    $this->cascadeMergeCollection($managedCol, $mapping);
                } elseif ('referrers' === $mapping['type']) {
                    $managedCol = $prop->getValue($managedCopy);
                    if (!$managedCol) {
                        $referringMeta = $this->dm->getClassMetadata($mapping['referringDocument']);
                        $referringField = $referringMeta->mappings[$mapping['referencedBy']];
                        $managedCol = new ReferrersCollection(
                            $this->dm,
                            $managedCopy,
                            $referringField['strategy'],
                            $referringField['property'],
                            $locale
                        );
                        $prop->setValue($managedCopy, $managedCol);
                        $this->originalData[$managedOid][$fieldName] = $managedCol;
                    }
                    $this->cascadeMergeCollection($managedCol, $mapping);
                } elseif ('mixedreferrers' === $mapping['type']) {
                    $managedCol = $prop->getValue($managedCopy);
                    if (!$managedCol) {
                        $managedCol = new ImmutableReferrersCollection(
                            $this->dm,
                            $managedCopy,
                            $mapping['referenceType'],
                            $locale
                        );
                        $prop->setValue($managedCopy, $managedCol);
                        $this->originalData[$managedOid][$fieldName] = $managedCol;
                    }
                    $this->cascadeMergeCollection($managedCol, $mapping);
                } elseif ('parent' === $mapping['type']) {
                    $this->doMergeSingleDocumentProperty($managedCopy, $other, $prop, $mapping);
                } elseif (in_array($mapping['type'], array('locale', 'versionane', 'versioncreated', 'node', 'nodename'))) {
                    if (null !== $other) {
                        $prop->setValue($managedCopy, $other);
                    }
                } elseif (!$class->isIdentifier($fieldName)) {
                    $prop->setValue($managedCopy, $other);
                }
            }

            if ($persist) {
                $this->persistNew($class, $managedCopy);
            }

            // Mark the managed copy visited as well
            $visited[$managedOid] = true;
        }

        if ($prevManagedCopy !== null) {
            $prevClass = $this->dm->getClassMetadata(get_class($prevManagedCopy));
            if ($assoc['type'] == ClassMetadata::MANY_TO_ONE) {
                $prevClass->reflFields[$assoc['fieldName']]->setValue($prevManagedCopy, $managedCopy);
            } else {
                $prevClass->reflFields[$assoc['fieldName']]->getValue($prevManagedCopy)->add($managedCopy);
            }
        }

        $this->cascadeMerge($class, $document, $managedCopy, $visited);

        return $managedCopy;
    }

    /**
* Cascades a merge operation to associated entities.
*
* @param ClassMetadata $class
* @param object $document
* @param object $managedCopy
* @param array $visited
*/
    private function cascadeMerge(ClassMetadata $class, $document, $managedCopy, array &$visited)
    {
        foreach (array_merge($class->referenceMappings, $class->referrersMappings) as $fieldName) {
            $mapping = $class->mappings[$fieldName];
            if (!($mapping['cascade'] & ClassMetadata::CASCADE_MERGE)) {
                continue;
            }
            $related = $class->reflFields[$fieldName]->getValue($document);
            if ($related instanceof Collection || is_array($related)) {
                if ($related instanceof PersistentCollection) {
                    // Unwrap so that foreach() does not initialize
                    $related = $related->unwrap();
                }
                foreach ($related as $relatedDocument) {
                    $this->doMerge($relatedDocument, $visited, $managedCopy, $mapping);
                }
            } elseif ($related !== null) {
                $this->doMerge($related, $visited, $managedCopy, $mapping);
            }
        }
    }

    /**
* Detaches a document from the persistence management. It's persistence will
* no longer be managed by Doctrine.
*
* @param object $document The document to detach.
*/
    public function detach($document)
    {
        $visited = array();
        $this->doDetach($document, $visited);
    }

    /**
* Executes a detach operation on the given document.
*
* @param object $document
* @param array $visited
*/
    private function doDetach($document, array &$visited)
    {
        $oid = spl_object_hash($document);
        if (isset($visited[$oid])) {
            return; // Prevent infinite recursion
        }

        $visited[$oid] = $document; // mark visited

        $class = $this->dm->getClassMetadata(get_class($document));
        $this->cascadeDetach($class, $document, $visited);

        $state = $this->getDocumentState($document);
        switch ($state) {
            case self::STATE_MANAGED:
                $this->unregisterDocument($document);
                break;
            case self::STATE_NEW:
            case self::STATE_DETACHED:
                return;
        }
    }

    private function cascadeRefresh(ClassMetadata $class, $document, &$visited)
    {
        foreach (array_merge($class->referenceMappings, $class->referrersMappings) as $fieldName) {
            $mapping = $class->mappings[$fieldName];
            if (!($mapping['cascade'] & ClassMetadata::CASCADE_REFRESH)) {
                continue;
            }

            $related = $class->reflFields[$fieldName]->getValue($document);
            if ($related instanceof Collection || is_array($related)) {
                if ($related instanceof PersistentCollection) {
                    // Unwrap so that foreach() does not initialize
                    $related = $related->unwrap();
                }
                foreach ($related as $relatedDocument) {
                    $this->doRefresh($relatedDocument, $visited);
                }
            } elseif ($related !== null) {
                $this->doRefresh($related, $visited);
            }
        }
    }

    /**
* Cascades a detach operation to associated documents.
*
* @param object $document
* @param array $visited
*/
    private function cascadeDetach(ClassMetadata $class, $document, array &$visited)
    {
        foreach ($class->childrenMappings as $fieldName) {
            $mapping = $class->mappings[$fieldName];
            if (!($mapping['cascade'] & ClassMetadata::CASCADE_DETACH)) {
                continue;
            }
            $related = $class->reflFields[$fieldName]->getValue($document);
            if ($related instanceof Collection || is_array($related)) {
                foreach ($related as $relatedDocument) {
                    $this->doDetach($relatedDocument, $visited);
                }
            } elseif ($related !== null) {
                $this->doDetach($related, $visited);
            }
        }

        foreach (array_merge($class->referenceMappings, $class->referrersMappings) as $fieldName) {
            $mapping = $class->mappings[$fieldName];
            if (!($mapping['cascade'] & ClassMetadata::CASCADE_DETACH)) {
                continue;
            }
            $related = $class->reflFields[$fieldName]->getValue($document);
            if ($related instanceof Collection || is_array($related)) {
                foreach ($related as $relatedDocument) {
                    $this->doDetach($relatedDocument, $visited);
                }
            } elseif ($related !== null) {
                $this->doDetach($related, $visited);
            }
        }

        // no cascade for mixed referrers
    }

    /**
* Commits the UnitOfWork
*
* @param object|array|null $document optionally limit to a specific
* document or an array of documents
*/
    public function commit($document = null)
    {
        // Raise preFlush
        if ($this->evm->hasListeners(Event::preFlush)) {
            $this->evm->dispatchEvent(Event::preFlush, new ManagerEventArgs($this->dm));
        }

        if ($document === null) {
            $this->computeChangeSets();
        } elseif (is_object($document)) {
            $this->computeSingleDocumentChangeSet($document);
        } elseif (is_array($document)) {
            foreach ($document as $object) {
                $this->computeSingleDocumentChangeSet($object);
            }
        }

        if ($this->evm->hasListeners(Event::onFlush)) {
            $this->evm->dispatchEvent(Event::onFlush, new ManagerEventArgs($this->dm));
        }

        try {
            $utx = $this->session->getWorkspace()->getTransactionManager();
            if ($utx->inTransaction()) {
                $utx = null;
            } else {
                $utx->begin();
            }
        } catch (UnsupportedRepositoryOperationException $e) {
            $utx = null;
        }

        try {
            $this->executeInserts($this->scheduledInserts);

            $this->executeUpdates($this->scheduledUpdates);

            $this->executeRemovals($this->scheduledRemovals);

            $this->executeReorders($this->scheduledReorders);

            $this->executeMoves($this->scheduledMoves);

            $this->session->save();

            if ($utx) {
                $utx->commit();
            }
        } catch (\Exception $e) {
            try {
                $this->dm->close();

                if ($utx) {
                    $utx->rollback();
                }
            } catch (\Exception $innerException) {
                //TODO: log error while closing dm after error: $innerException->getMessage
            }
            throw $e;
        }

        foreach ($this->visitedCollections as $col) {
            $col->takeSnapshot();
        }

        // Raise postFlush
        if ($this->evm->hasListeners(Event::postFlush)) {
            $this->evm->dispatchEvent(Event::postFlush, new ManagerEventArgs($this->dm));
        }

        if (null === $document) {
            $this->documentTranslations = array();
            foreach ($this->documentLocales as $oid => $locales) {
                $this->documentLocales[$oid]['original'] = $locales['current'];
            }
        } else {
            $documents = is_array($document) ? $document : array($document);
            foreach ($documents as $doc) {
                $oid = spl_object_hash($doc);
                unset($this->documentTranslations[$oid]);
                if (isset($this->documentLocales[$oid])) {
                    $this->documentLocales[$oid]['original'] = $this->documentLocales[$oid]['current'];
                }
            }
        }

        $this->scheduledUpdates =
        $this->scheduledRemovals =
        $this->scheduledMoves =
        $this->scheduledReorders =
        $this->scheduledInserts =
        $this->visitedCollections =
        $this->documentChangesets =
        $this->changesetComputed = array();
    }

    /**
* Executes all document insertions
*
* @param array $documents array of all to be inserted documents
*/
    private function executeInserts($documents)
    {
        // sort the documents to insert parents first but maintain child order
        $oids = array();
        foreach ($documents as $oid => $document) {
            if (!$this->contains($oid)) {
                continue;
            }

            $oids[$oid] = $this->getDocumentId($document);
        }

        $order = array_flip(array_values($oids));
        uasort($oids, function ($a, $b) use ($order) {
                // compute the node depths
                $aCount = substr_count($a, '/');
                $bCount = substr_count($b, '/');

                // ensure that the original order is maintained for nodes with the same depth
                if ($aCount === $bCount) {
                    return ($order[$a] < $order[$b]) ? -1 : 1;
                }

                return ($aCount < $bCount) ? -1 : 1;
            }
        );

        $associationChangesets = $associationUpdates = array();

        foreach ($oids as $oid => $id) {
            $document = $documents[$oid];
            $class = $this->dm->getClassMetadata(get_class($document));

            // PHPCR does not validate nullable unless we would start to
            // generate custom node types, which we at the moment don't.
            // the ORM can delegate this validation to the relational database
            // that is using a strict schema
            foreach ($class->fieldMappings as $fieldName) {
                if (!isset($this->documentChangesets[$oid]['fields'][$fieldName]) // empty string is ok
                    && !$class->isNullable($fieldName)
                    && !$this->isAutocreatedProperty($class, $fieldName)
                ) {
                    throw new PHPCRException(sprintf('Field "%s" of class "%s" is not nullable', $fieldName, $class->name));
                }
            }

            $parentNode = $this->session->getNode(PathHelper::getParentPath($id));
            $nodename = PathHelper::getNodeName($id);
            $node = $parentNode->addNode($nodename, $class->nodeType);
            if ($class->node) {
                $this->originalData[$oid][$class->node] = $node;
            }
            if ($class->nodename) {
                $this->originalData[$oid][$class->nodename] = $nodename;
            }

            try {
                $node->addMixin('phpcr:managed');
            } catch (NoSuchNodeTypeException $e) {
                throw new PHPCRException('Register phpcr:managed node type first. See https://github.com/doctrine/phpcr-odm/wiki/Custom-node-type-phpcr:managed');
            }

            foreach ($class->mixins as $mixin) {
                $node->addMixin($mixin);
            }

            if ($class->identifier) {
                $class->setIdentifierValue($document, $id);
            }
            if ($class->node) {
                $class->reflFields[$class->node]->setValue($document, $node);
            }
            if ($class->nodename) {
                // make sure this reflects the id generator strategy generated id
                $class->reflFields[$class->nodename]->setValue($document, $node->getName());
            }
            // make sure this reflects the id generator strategy generated id
            if ($class->parentMapping && !$class->reflFields[$class->parentMapping]->getValue($document)) {
                $class->reflFields[$class->parentMapping]->setValue($document, $this->getOrCreateProxyFromNode($parentNode, $this->getCurrentLocale($document, $class)));
            }

            if ($this->writeMetadata) {
                $this->documentClassMapper->writeMetadata($this->dm, $node, $class->name);
            }

            $this->setMixins($class, $node, $document);


            foreach ($this->documentChangesets[$oid]['fields'] as $fieldName => $fieldValue) {
                // Ignore translatable fields (they will be persisted by the translation strategy)
                if (in_array($fieldName, $class->translatableFields)) {
                    continue;
                }

                if (in_array($fieldName, $class->fieldMappings)) {
                    $mapping = $class->mappings[$fieldName];
                    $type = PropertyType::valueFromName($mapping['type']);
                    if (null === $fieldValue) {
                        continue;
                    }

                    if ($mapping['multivalue'] && $fieldValue) {
                        $fieldValue = (array) $fieldValue;
                        if (isset($mapping['assoc'])) {
                            $fieldValue = $this->processAssoc($node, $mapping, $fieldValue);
                        }
                    }

                    $node->setProperty($mapping['property'], $fieldValue, $type);
                } elseif (in_array($fieldName, $class->referenceMappings) || in_array($fieldName, $class->referrersMappings)) {
                    $associationUpdates[$oid] = $document;

                    //populate $associationChangesets to force executeUpdates($associationUpdates)
                    //to only update association fields
                    $data = isset($associationChangesets[$oid]['fields']) ? $associationChangesets[$oid]['fields'] : array();
                    $data[$fieldName] = $fieldValue;
                    $associationChangesets[$oid] = array('fields' => $data, 'reorderings' => array());
                }
            }

            $this->doSaveTranslation($document, $node, $class);

            if (isset($class->lifecycleCallbacks[Event::postPersist])) {
                $class->invokeLifecycleCallbacks(Event::postPersist, $document);
            }
            if ($this->evm->hasListeners(Event::postPersist)) {
                $this->evm->dispatchEvent(Event::postPersist, new LifecycleEventArgs($document, $this->dm));
            }
        }

        $this->documentChangesets = array_merge($this->documentChangesets, $associationChangesets);

        $this->executeUpdates($associationUpdates, false);
    }

    /**
* Identify whether a PHPCR property is autocreated or not.
*
* @param ClassMetadata $class
* @param string $fieldName
*
* @return boolean
*/
    private function isAutocreatedProperty(ClassMetadata $class, $fieldName)
    {
        $field = $class->getField($fieldName);
        if ('jcr:uuid' === $field['property']) {
            // jackrabbit at least does not identify this as auto created
            // it is strictly speaking no property
            return true;
        }
        $ntm = $this->session->getWorkspace()->getNodeTypeManager();
        $nodeType = $ntm->getNodeType($class->getNodeType());
        $propertyDefinitions = $nodeType->getPropertyDefinitions();
        foreach ($class->getMixins() as $mixinTypeName) {
            $nodeType = $ntm->getNodeType($mixinTypeName);
            $propertyDefinitions = array_merge($propertyDefinitions, $nodeType->getPropertyDefinitions());
        }

        foreach ($propertyDefinitions as $property) {
            if ($class->mappings[$fieldName]['property'] === $property->getName()
                && $property->isAutoCreated()
            ) {
                return true;
            }
        }

        return false;
    }

    /**
* Executes all document updates
*
* @param array $documents array of all to be updated documents
* @param boolean $dispatchEvents if to dispatch events
*/
    private function executeUpdates($documents, $dispatchEvents = true)
    {
        foreach ($documents as $oid => $document) {
            if (!$this->contains($oid)) {
                continue;
            }

            $class = $this->dm->getClassMetadata(get_class($document));
            $node = $this->session->getNode($this->getDocumentId($document));

            if ($this->writeMetadata) {
                $this->documentClassMapper->writeMetadata($this->dm, $node, $class->name);
            }

            if ($dispatchEvents) {
                if (isset($class->lifecycleCallbacks[Event::preUpdate])) {
                    $class->invokeLifecycleCallbacks(Event::preUpdate, $document);
                    $this->changesetComputed = array_diff($this->changesetComputed, array($oid));
                    $this->computeChangeSet($class, $document);
                }
                if ($this->evm->hasListeners(Event::preUpdate)) {
                    $this->evm->dispatchEvent(Event::preUpdate, new LifecycleEventArgs($document, $this->dm));
                    $this->changesetComputed = array_diff($this->changesetComputed, array($oid));
                    $this->computeChangeSet($class, $document);
                }
            }

            foreach ($this->documentChangesets[$oid]['fields'] as $fieldName => $fieldValue) {
                // PHPCR does not validate nullable unless we would start to
                // generate custom node types, which we at the moment don't.
                // the ORM can delegate this validation to the relational database
                // that is using a strict schema.
                // do this after the preUpdate events to give listener a last
                // chance to provide values
                if (null === $fieldValue
                    && in_array($fieldName, $class->fieldMappings) // only care about non-virtual fields
                    && !$class->isNullable($fieldName)
                    && !$this->isAutocreatedProperty($class, $fieldName)
                ) {
                    throw new PHPCRException(sprintf('Field "%s" of class "%s" is not nullable', $fieldName, $class->name));
                }

                // Ignore translatable fields (they will be persisted by the translation strategy)
                if (in_array($fieldName, $class->translatableFields)) {
                    continue;
                }

                $mapping = $class->mappings[$fieldName];
                if (in_array($fieldName, $class->fieldMappings)) {
                    $type = PropertyType::valueFromName($mapping['type']);
                    if ($mapping['multivalue']) {
                        $value = empty($fieldValue) ? null : ($fieldValue instanceof Collection ? $fieldValue->toArray() : $fieldValue);
                        if ($value && isset($mapping['assoc'])) {
                            $value = $this->processAssoc($node, $mapping, $value);
                        }
                    } else {
                        $value = $fieldValue;
                    }
                    $node->setProperty($mapping['property'], $value, $type);
                } elseif ($mapping['type'] === $class::MANY_TO_ONE
                    || $mapping['type'] === $class::MANY_TO_MANY
                ) {
                    if (!$this->writeMetadata) {
                        continue;
                    }
                    if ($node->hasProperty($mapping['property']) && is_null($fieldValue)) {
                        $node->getProperty($mapping['property'])->remove();
                        continue;
                    }

                    switch ($mapping['strategy']) {
                        case 'hard':
                            $strategy = PropertyType::REFERENCE;
                            break;
                        case 'path':
                            $strategy = PropertyType::PATH;
                            break;
                        default:
                            $strategy = PropertyType::WEAKREFERENCE;
                            break;
                    }

                    if ($mapping['type'] === $class::MANY_TO_MANY) {
                        if (isset($fieldValue)) {
                            $refNodesIds = array();
                            foreach ($fieldValue as $fv) {
                                if ($fv === null) {
                                    continue;
                                }

                                $associatedNode = $this->session->getNode($this->getDocumentId($fv));
                                if ($strategy === PropertyType::PATH) {
                                    $refNodesIds[] = $associatedNode->getPath();
                                } else {
                                    $refClass = $this->dm->getClassMetadata(get_class($fv));
                                    $this->setMixins($refClass, $associatedNode, $fv);
                                    if (!$associatedNode->isNodeType('mix:referenceable')) {
                                        throw new PHPCRException(sprintf('Referenced document %s is not referenceable. Use referenceable=true in Document annotation: '.self::objToStr($document, $this->dm), ClassUtils::getClass($fv)));
                                    }
                                    $refNodesIds[] = $associatedNode->getIdentifier();
                                }
                            }

                            $refNodesIds = empty($refNodesIds) ? null : $refNodesIds;
                            $node->setProperty($mapping['property'], $refNodesIds, $strategy);
                        }
                    } elseif ($mapping['type'] === $class::MANY_TO_ONE) {
                        if (isset($fieldValue)) {
                            $associatedNode = $this->session->getNode($this->getDocumentId($fieldValue));

                            if ($strategy === PropertyType::PATH) {
                                $node->setProperty($fieldName, $associatedNode->getPath(), $strategy);
                            } else {
                                $refClass = $this->dm->getClassMetadata(get_class($fieldValue));
                                $this->setMixins($refClass, $associatedNode, $document);
                                if (!$associatedNode->isNodeType('mix:referenceable')) {
                                    throw new PHPCRException(sprintf('Referenced document %s is not referenceable. Use referenceable=true in Document annotation: '.self::objToStr($document, $this->dm), ClassUtils::getClass($fieldValue)));
                                }
                                $node->setProperty($mapping['property'], $associatedNode->getIdentifier(), $strategy);
                            }
                        }
                    }
                } elseif ('referrers' === $mapping['type']) {
                    if (isset($fieldValue)) {

                        /*
* each document in referrers field is supposed to
* reference this document, so we have to update its
* referencing property to contain the uuid of this
* document
*/
                        foreach ($fieldValue as $fv) {
                            if ($fv === null) {
                                continue;
                            }

                            if (! $fv instanceof $mapping['referringDocument']) {
                                throw new PHPCRException(sprintf("%s is not an instance of %s for document %s field %s", self::objToStr($fv, $this->dm), $mapping['referencedBy'], self::objToStr($document, $this->dm), $mapping['fieldName']));
                            }

                            $referencingNode = $this->session->getNode($this->getDocumentId($fv));
                            $referencingMeta = $this->dm->getClassMetadata($mapping['referringDocument']);
                            $referencingField = $referencingMeta->getAssociation($mapping['referencedBy']);

                            $uuid = $node->getIdentifier();
                            $strategy = $referencingField['strategy'] == 'weak' ? PropertyType::WEAKREFERENCE : PropertyType::REFERENCE;
                            switch ($referencingField['type']) {
                                case ClassMetadata::MANY_TO_ONE:
                                    $ref = $referencingMeta->getFieldValue($fv, $referencingField['fieldName']);
                                    if ($ref !== null && $ref !== $document) {
                                        throw new PHPCRException(sprintf('Conflicting settings for referrer and reference: Document %s field %s points to %s but document %s has set first document as referrer on field %s', self::objToStr($fv, $this->dm), $referencingField['fieldName'], self::objToStr($ref, $this->dm), self::objToStr($document, $this->dm), $mapping['fieldName']));
                                    }
                                    // update the referencing document field to point to this document
                                    $referencingMeta->setFieldValue($fv, $referencingField['fieldName'], $document);
                                    // and make sure the reference is not deleted in this change because the field could be null
                                    unset($this->documentChangesets[spl_object_hash($fv)]['fields'][$referencingField['fieldName']]);
                                    // store the change in PHPCR
                                    $referencingNode->setProperty($referencingField['property'], $uuid, $strategy);
                                    break;
                                case ClassMetadata::MANY_TO_MANY:
                                    /** @var $collection ReferenceManyCollection */
                                    $collection = $referencingMeta->getFieldValue($fv, $referencingField['fieldName']);
                                    if ($collection instanceof PersistentCollection && $collection->isDirty()) {
                                        throw new PHPCRException(sprintf('You may not modify the reference and referrer collections of interlinked documents as this is ambiguous. Reference %s on document %s and referrers %s on document %s are both modified', self::objToStr($fv, $this->dm), $referencingField['fieldName']), self::objToStr($document, $this->dm), $mapping['fieldName']);
                                    }
                                    if ($collection) {
                                        // make sure the reference is not deleted in this change because the field could be null
                                        unset($this->documentChangesets[spl_object_hash($fv)]['fields'][$referencingField['fieldName']]);
                                    } else {
                                        $collection = new ReferenceManyCollection($this->dm, array($node), $class->name);
                                        $referencingMeta->setFieldValue($fv, $referencingField['fieldName'], $collection);
                                    }

                                    if ($referencingNode->hasProperty($referencingField['property'])) {
                                        if (! in_array($uuid, $referencingNode->getPropertyValue($referencingField['property']), PropertyType::STRING)) {
                                            if (!$collection instanceof PersistentCollection || !$collection->isDirty()) {
                                                // update the reference collection: add us to it
                                                $collection->add($document);
                                            }
                                            // store the change in PHPCR
                                            $referencingNode->getProperty($referencingField['property'])->addValue($uuid); // property should be correct type already
                                        }
                                    } else {
                                        // store the change in PHPCR
                                        $referencingNode->setProperty($referencingField['property'], array($uuid), $strategy);
                                    }

                                    // avoid confusion later, this change to the reference collection is already saved
                                    $collection->setDirty(false);
                                    break;
                                default:
                                    // in class metadata we only did a santiy check but not look at the actual mapping
                                    throw new MappingException(sprintf('Field "%s" of document "%s" is not a reference field. Error in referrer annotation: '.self::objToStr($document, $this->dm), $mapping['referencedBy'], ClassUtils::getClass($fv)));
                            }
                        }
                    }
                } elseif ('child' === $mapping['type']) {
                    if ($fieldValue === null && $node->hasNode($mapping['nodeName'])) {
                        $child = $node->getNode($mapping['nodeName']);
                        $childDocument = $this->getOrCreateDocument(null, $child);
                        $this->purgeChildren($childDocument);
                        $child->remove();
                    }
                }
            }

            foreach ($this->documentChangesets[$oid]['reorderings'] as $reorderings) {
                foreach ($reorderings as $srcChildRelPath => $destChildRelPath) {
                    $node->orderBefore($srcChildRelPath, $destChildRelPath);
                }
            }

            $this->doSaveTranslation($document, $node, $class);

            if ($dispatchEvents) {
                if (isset($class->lifecycleCallbacks[Event::postUpdate])) {
                    $class->invokeLifecycleCallbacks(Event::postUpdate, $document);
                }
                if ($this->evm->hasListeners(Event::postUpdate)) {
                    $this->evm->dispatchEvent(Event::postUpdate, new LifecycleEventArgs($document, $this->dm));
                }
            }
        }
    }

    /**
* Executes all document moves
*
* @param array $documents array of all to be moved documents
*/
    private function executeMoves($documents)
    {
        foreach ($documents as $oid => $value) {
            if (!$this->contains($oid)) {
                continue;
            }

            list($document, $targetPath) = $value;

            $sourcePath = $this->getDocumentId($document);
            if ($sourcePath === $targetPath) {
                continue;
            }

            $class = $this->dm->getClassMetadata(get_class($document));
            if (isset($class->lifecycleCallbacks[Event::preMove])) {
                $class->invokeLifecycleCallbacks(Event::preMove, $document);
            }

            if ($this->evm->hasListeners(Event::preMove)) {
                $this->evm->dispatchEvent(Event::preMove, new MoveEventArgs($document, $this->dm, $sourcePath, $targetPath));
            }

            $this->session->move($sourcePath, $targetPath);

            // update fields nodename and parentMapping if they exist in this type
            $node = $this->session->getNode($targetPath); // get node from session, document class might not map it
            if ($class->nodename) {
                $class->setFieldValue($document, $class->nodename, $node->getName());
            }

            if ($class->parentMapping) {
                $class->setFieldValue($document, $class->parentMapping, $this->getOrCreateProxyFromNode($node->getParent(), $this->getCurrentLocale($document, $class)));
            }

            // update all cached children of the document to reflect the move (path id changes)
            foreach ($this->documentIds as $childOid => $id) {
                if (0 !== strpos($id, $sourcePath)) {
                    continue;
                }

                $newId = $targetPath.substr($id, strlen($sourcePath));
                $this->documentIds[$childOid] = $newId;

                $child = $this->getDocumentById($id);
                if (!$child) {
                    continue;
                }

                unset($this->identityMap[$id]);
                $this->identityMap[$newId] = $child;

                $childClass = $this->dm->getClassMetadata(get_class($child));
                if ($childClass->identifier) {
                    $childClass->setIdentifierValue($child, $newId);
                    if (! $child instanceof Proxy || $child->__isInitialized()) {
                        $this->originalData[$oid][$childClass->identifier] = $newId;
                    }
                }
            }

            if (isset($class->lifecycleCallbacks[Event::postMove])) {
                $class->invokeLifecycleCallbacks(Event::postMove, $document);
            }

            if ($this->evm->hasListeners(Event::postMove)) {
                $this->evm->dispatchEvent(Event::postMove, new MoveEventArgs($document, $this->dm, $sourcePath, $targetPath));
            }
        }
    }

    /**
* Execute reorderings
*
* @param $documents
*/
    private function executeReorders($documents)
    {
        foreach ($documents as $oid => $list) {
            if (!$this->contains($oid)) {
                continue;
            }
            foreach ($list as $value) {
                list($parent, $src, $target, $before) = $value;
                $parentNode = $this->session->getNode($this->getDocumentId($parent));

                // check for src and target ...
                $dest = $target;
                if ($parentNode->hasNode($src) && $parentNode->hasNode($target)) {
                    // there is no orderAfter, so we need to find the child after target to use it in orderBefore
                    if (!$before) {
                        $dest = null;
                        $found = false;
                        foreach ($parentNode->getNodes() as $name => $child) {
                            if ($name === $target) {
                                $found = true;
                            } elseif ($found) {
                                $dest = $name;
                                break;
                            }
                        }
                    }

                    $parentNode->orderBefore($src, $dest);
                    // set all children collection to initialized = false to force reload after reordering
                    $class = $this->dm->getClassMetadata(get_class($parent));
                    foreach ($class->childrenMappings as $fieldName) {
                        $children = $class->reflFields[$fieldName]->getValue($parent);
                        if ($children instanceof PersistentCollection) {
                            $children->setInitialized(false);
                        }
                    }
                }
            }
        }
    }

    /**
* Executes all document removals
*
* @param array $documents array of all to be removed documents
*/
    private function executeRemovals($documents)
    {
        foreach ($documents as $oid => $document) {
            if (empty($this->documentIds[$oid])) {
                continue;
            }

            $class = $this->dm->getClassMetadata(get_class($document));
            $id = $this->getDocumentId($document);

            try {
                $node = $this->session->getNode($id);
                $this->doRemoveAllTranslations($document, $class);
                $node->remove();
            } catch (PathNotFoundException $e) {
            }

            $this->unregisterDocument($document);
            $this->purgeChildren($document);

            if (isset($class->lifecycleCallbacks[Event::postRemove])) {
                $class->invokeLifecycleCallbacks(Event::postRemove, $document);
            }
            if ($this->evm->hasListeners(Event::postRemove)) {
                $this->evm->dispatchEvent(Event::postRemove, new LifecycleEventArgs($document, $this->dm));
            }
        }
    }

    /**
* @see DocumentManager::findVersionByName
*/
    public function findVersionByName($className, $id, $versionName)
    {
        $versionManager = $this->session
            ->getWorkspace()
            ->getVersionManager();

        try {
            $history = $versionManager->getVersionHistory($id);
        } catch (ItemNotFoundException $e) {
            // there is no document with $id
            return null;
        } catch (UnsupportedRepositoryOperationException $e) {
            throw new InvalidArgumentException("Document with id $id is not versionable", $e->getCode(), $e);
        }

        try {
            $version = $history->getVersion($versionName);
            $node = $version->getFrozenNode();
        } catch (RepositoryException $e) {
            throw new InvalidArgumentException("No version $versionName on document $id", $e->getCode(), $e);
        }

        $hints = array('versionName' => $versionName, 'ignoreHardReferenceNotFound' => true);
        $frozenDocument = $this->getOrCreateDocument($className, $node, $hints);
        $this->dm->detach($frozenDocument);

        $oid = spl_object_hash($frozenDocument);
        $this->documentHistory[$oid] = $history;
        $this->documentVersion[$oid] = $version;

        // Set the annotations
        $metadata = $this->dm->getClassMetadata(get_class($frozenDocument));
        if ($metadata->versionNameField) {
            $metadata->reflFields[$metadata->versionNameField]->setValue($frozenDocument, $versionName);
        }
        if ($metadata->versionCreatedField) {
            $metadata->reflFields[$metadata->versionCreatedField]->setValue($frozenDocument, $version->getCreated());
        }

        return $frozenDocument;
    }

    /**
* Checkin operation - Save all current changes and then check in the Node by id.
*/
    public function checkin($document)
    {
        $path = $this->getFullVersionedNodePath($document);
        $vm = $this->session->getWorkspace()->getVersionManager();
        $vm->checkin($path); // Checkin Node aka make a new Version
    }

    /**
* Check out operation - Save all current changes and then check out the
* Node by path.
*/
    public function checkout($document)
    {
        $path = $this->getFullVersionedNodePath($document);
        $vm = $this->session->getWorkspace()->getVersionManager();
        $vm->checkout($path);
    }

    /**
* Create a version of the document and check it out right again to
* continue editing.
*/
    public function checkpoint($document)
    {
        $path = $this->getFullVersionedNodePath($document);
        $vm = $this->session->getWorkspace()->getVersionManager();
        $vm->checkpoint($path);
    }

    /**
* Get the version history information for a document
*
* TODO: implement labels once jackalope implements them, until then labels will be an empty array.
* TODO: implement limit
*
* @param object $document the document of which to get the version history
* @param int $limit an optional limit to only get the latest $limit information
*
* @return array of <versionname> => array("name" => <versionname>, "labels" => <array of labels>, "created" => <DateTime>)
* oldest version first
*/
    public function getAllLinearVersions($document, $limit = -1)
    {
        $path = $this->getDocumentId($document);
        $metadata = $this->dm->getClassMetadata(get_class($document));

        if (!$metadata->versionable) {
            throw new InvalidArgumentException(sprintf("The document of type '%s' is not versionable", $metadata->getName()));
        }

        $versions = $this->session
            ->getWorkspace()
            ->getVersionManager()
            ->getVersionHistory($path)
            ->getAllLinearVersions();

        $result = array();
        foreach ($versions as $version) {
            /** @var $version \PHPCR\Version\VersionInterface */
            $result[$version->getName()] = array(
                'name' => $version->getName(),
                'labels' => array(),
                'created' => $version->getCreated(),
            );
        }

        return $result;
    }

    /**
* Restore the document to the state it was before
*
* @param string $documentVersion the version name to restore
* @param boolean $removeExisting how to handle identifier collisions
*
* @see VersionManager::restore
*/
    public function restoreVersion($documentVersion, $removeExisting)
    {
        $oid = spl_object_hash($documentVersion);
        $history = $this->documentHistory[$oid];
        $version = $this->documentVersion[$oid];
        $document = $this->dm->find(null, $history->getVersionableIdentifier());
        $vm = $this->session->getWorkspace()->getVersionManager();

        $vm->restore($removeExisting, $version);
        $this->dm->refresh($document);
    }

    /**
* Delete an old version of a document
*
* @param string $documentVersion the version name
*/
    public function removeVersion($documentVersion)
    {
        $oid = spl_object_hash($documentVersion);
        $history = $this->documentHistory[$oid];
        $version = $this->documentVersion[$oid];

        $history->removeVersion($version->getName());

        unset($this->documentVersion[$oid]);
        unset($this->documentHistory[$oid]);
    }

    /**
* Removes a document from the identity map. This effectively detaches the
* document from the persistence management of Doctrine.
*
* @param object $document
*/
    private function unregisterDocument($document)
    {
        $oid = spl_object_hash($document);

        if (isset($this->documentIds[$oid])) {
            unset($this->identityMap[$this->documentIds[$oid]]);
        }

        unset($this->scheduledRemovals[$oid],
            $this->scheduledUpdates[$oid],
            $this->scheduledMoves[$oid],
            $this->scheduledReorders[$oid],
            $this->scheduledInserts[$oid],
            $this->originalData[$oid],
            $this->documentIds[$oid],
            $this->documentState[$oid],
            $this->documentTranslations[$oid],
            $this->documentLocales[$oid],
            $this->nonMappedData[$oid],
            $this->documentChangesets[$oid],
            $this->documentHistory[$oid],
            $this->documentVersion[$oid]
        );

        $this->changesetComputed = array_diff($this->changesetComputed, array($oid));
    }

    /**
* @param object $document
* @param string $id The document id to look for.
*
* @return string generated object hash
*/
    public function registerDocument($document, $id)
    {
        $oid = spl_object_hash($document);
        $this->documentIds[$oid] = $id;
        $this->identityMap[$id] = $document;
        $this->setDocumentState($oid, self::STATE_MANAGED);

        return $oid;
    }

    /**
* @param object|string $document document instance or document object hash
*
* @return boolean
*/
    public function contains($document)
    {
        $oid = is_object($document) ? spl_object_hash($document) : $document;

        return isset($this->documentIds[$oid]) && !isset($this->scheduledRemovals[$oid]);
    }

    /**
* Tries to find a document with the given id in the identity map of
* this UnitOfWork.
*
* @param string $id The document id to look for.
* @param string $rootClassName The name of the root class of the mapped document hierarchy.
*
* @return object|false Returns the document with the specified id if it exists in
* this UnitOfWork, FALSE otherwise.
*/
    public function getDocumentById($id)
    {
        if (isset($this->identityMap[$id])) {
            return $this->identityMap[$id];
        }

        return false;
    }

    /**
* Get the object ID for the given document
*
* @param object|string $document document instance or document object hash
*
* @return string|null
*
* @throws PHPCRException
*/
    public function getDocumentId($document, $throw = true)
    {
        $oid = is_object($document) ? spl_object_hash($document) : $document;
        if (empty($this->documentIds[$oid])) {
            if (!$throw) {
                return null;
            }
            $msg = 'Document is not managed and has no id';
            if (is_object($document)) {
                $msg.= ': '.self::objToStr($document);
            }
            throw new PHPCRException($msg);
        }

        return $this->documentIds[$oid];
    }

    /**
* Try to determine the document id first by looking into the document,
* but if not mapped, look into the document id cache.
*
* @param object $document
* @param ClassMetadata $metadata
*
* @return string|null the current or stored id, or null if nothing can be found.
*/
    public function determineDocumentId($document, ClassMetadata $metadata = null)
    {
        if (!$metadata) {
            $metadata = $this->dm->getClassMetadata(get_class($document));
        }
        if ($metadata->identifier) {
            $id = $metadata->getIdentifierValue($document);
            if ($id) {
                return $id;
            }
        }

        return $this->getDocumentId($document, false);
    }

    /**
* Helper method to initialize a lazy loading proxy or persistent collection.
*
* @param object
*/
    public function initializeObject($obj)
    {
        if ($obj instanceof Proxy) {
            $obj->__load();
        } elseif ($obj instanceof PersistentCollection) {
            $obj->initialize();
        }
    }

    /**
* Clears the UnitOfWork.
*/
    public function clear()
    {
        $this->identityMap =
        $this->documentIds =
        $this->documentState =
        $this->documentTranslations =
        $this->documentLocales =
        $this->nonMappedData =
        $this->originalData =
        $this->documentChangesets =
        $this->changesetComputed =
        $this->scheduledUpdates =
        $this->scheduledInserts =
        $this->scheduledMoves =
        $this->scheduledReorders =
        $this->scheduledRemovals =
        $this->visitedCollections =
        $this->documentHistory =
        $this->documentVersion = array();

        if ($this->evm->hasListeners(Event::onClear)) {
            $this->evm->dispatchEvent(Event::onClear, new ManagerEventArgs($this->dm));
        }

        $this->session->refresh(false);
    }

    /**
* Get all locales in which this document currently exists in storage.
*
* @param object $document A managed document
*
* @return array list of locales of this document
*
* @throws MissingTranslationException if this document is not translatable
*/
    public function getLocalesFor($document)
    {
        $metadata = $this->dm->getClassMetadata(get_class($document));
        if (!$this->isDocumentTranslatable($metadata)) {
            throw new MissingTranslationException('This document is not translatable: : '.self::objToStr($document, $this->dm));
        }

        $oid = spl_object_hash($document);
        if ($this->contains($oid)) {
            try {
                $node = $this->session->getNode($this->getDocumentId($document));
                $locales = $this->dm->getTranslationStrategy($metadata->translator)->getLocalesFor($document, $node, $metadata);
            } catch (PathNotFoundException $e) {
                $locales = array();
            }
        } else {
            $locales = array();
        }

        if (isset($this->documentTranslations[$oid])) {
            foreach ($this->documentTranslations[$oid] as $locale => $value) {
                if (!in_array($locale, $locales)) {
                    if ($value) {
                        $locales[] = $locale;
                    }
                } elseif (!$value) {
                    $key = array_search($locale, $locales);
                    unset($locales[$key]);
                }
            }

            $locales = array_values($locales);
        }

        return $locales;
    }

    private function doSaveTranslation($document, NodeInterface $node, $metadata)
    {
        if (!$this->isDocumentTranslatable($metadata)) {
            return;
        }

        $locale = $this->getCurrentLocale($document, $metadata);

        $oid = spl_object_hash($document);
        // handle case for initial persisting
        if (empty($this->documentTranslations[$oid])) {
            $this->bindTranslation($document, $locale);
        // handle case when locale in the mapped property changed
        } elseif (isset($this->documentLocales[$oid]['current'])
            && $locale !== $this->documentLocales[$oid]['current']
        ) {
            $this->bindTranslation($document, $locale);
        }

        if (!empty($this->documentTranslations[$oid])) {
            $strategy = $this->dm->getTranslationStrategy($metadata->translator);
            foreach ($this->documentTranslations[$oid] as $locale => $data) {
                if ($data) {
                    $strategy->saveTranslation($data, $node, $metadata, $locale);
                } else {
                    $strategy->removeTranslation($document, $node, $metadata, $locale);
                }
            }
        }
    }

    /**
* Load an in-memory bound translation if there is one in the requested
* locale. Does not attempt any fallback.
*
* @param object $document
* @param ClassMetadata $metadata
* @param string $locale
*
* @return boolean whether the pending translation in language $locale was
* loaded or not.
*
* @see doLoadTranslation
*/
    protected function doLoadPendingTranslation($document, ClassMetadata $metadata, $locale)
    {
        $oid = spl_object_hash($document);

        if (!isset($this->documentTranslations[$oid][$locale])) {
            return false;
        }

        $translations = $this->documentTranslations[$oid][$locale];
        foreach ($metadata->translatableFields as $field) {
            $metadata->reflFields[$field]->setValue($document, $translations[$field]);
        }

        return true;
    }

    /**
* Attempt to load translation from the database.
*
* If $fallback is true, goes over the locales as provided by the locale
* chooser strategy to find the best language, each time first checking for
* a pending translation. If no translation is found at all, the translated
* fields are set to null and the requested locale is considered to be the
* one found.
*
* @param object $document
* @param ClassMetadata $metadata
* @param string $locale
* @param boolean $fallback
*
* @return string The locale used
*
* @throws MissingTranslationException if the translation in $locale is not
* found and $fallback is false.
*
* @see doLoadTranslation
*/
    protected function doLoadDatabaseTranslation($document, ClassMetadata $metadata, $locale, $fallback)
    {
        $oid = spl_object_hash($document);

        $strategy = $this->dm->getTranslationStrategy($metadata->translator);
        try {
            $node = $this->session->getNode($this->getDocumentId($oid));
            if ($strategy->loadTranslation($document, $node, $metadata, $locale)) {
                return $locale;
            }
        } catch(PathNotFoundException $e) {
            // no node, document not persisted yet
            $node = null;
        }

        if (!$fallback) {
            $msg = sprintf('Document %s has no translation %s and fallback was not active', $this->getDocumentId($oid), $locale);
            throw new MissingTranslationException($msg);
        }

        $localesToTry = $this->dm->getLocaleChooserStrategy()->getFallbackLocales($document, $metadata, $locale);

        foreach ($localesToTry as $desiredLocale) {
            // if there is a pending translation, it wins
            if ($this->doLoadPendingTranslation($document, $metadata, $desiredLocale)) {
                return $desiredLocale;
            }
            // try loading the translation with strategy if this is a stored document
            if ($node && $strategy->loadTranslation($document, $node, $metadata, $desiredLocale)) {
                return $desiredLocale;
            }
        }

        // we found no locale. so all translated fields are null and we
        // consider the locale to be the requested one
        $localeUsed = $locale;
        foreach ($metadata->translatableFields as $fieldName) {
            $value = ($metadata->mappings[$fieldName]['multivalue']) ? array() : null;
            $metadata->reflFields[$fieldName]->setValue($document, $value);
        }

        return $locale;
    }

    /**
* Load the translatable fields of the document.
*
* If locale is not set then the current locale of the document is
* reloaded, resetting possible changes.
*
* If the document is not translatable, this method returns immediately
* and without error.
*
* @param object $document
* @param ClassMetadata $metadata
* @param string $locale The locale to use or null if the default locale should be used
* @param boolean $fallback Whether to do try other languages
*
* @throws MissingTranslationException if the translation in $locale is not
* found and $fallback is false.
*/
    public function doLoadTranslation($document, ClassMetadata $metadata, $locale = null, $fallback = false)
    {
        if (!$this->isDocumentTranslatable($metadata)) {
            return;
        }

        $currentLocale = $this->getCurrentLocale($document, $metadata);
        // if no locale is specified, we reset the current translation
        $locale = $locale ?: $currentLocale;

        if ($this->doLoadPendingTranslation($document, $metadata, $locale)) {
            $localeUsed = $locale;
        } else {
            $localeUsed = $this->doLoadDatabaseTranslation($document, $metadata, $locale, $fallback);
        }

        $this->setLocale($document, $metadata, $localeUsed);

        if ($metadata->parentMapping) {
            $parent = $metadata->reflFields[$metadata->parentMapping]->getValue($document);
            $this->cascadeDoLoadTranslation($parent, $metadata->mappings[$metadata->parentMapping], $locale);
        }

        if ($metadata->childMappings) {
            foreach ($metadata->childMappings as $fieldName) {
                $child = $metadata->reflFields[$fieldName]->getValue($document);
                $this->cascadeDoLoadTranslation($child, $metadata->mappings[$fieldName], $locale);
            }
        }

        if ($metadata->childrenMappings) {
            foreach ($metadata->childrenMappings as $fieldName) {
                $children = $metadata->reflFields[$fieldName]->getValue($document);
                if ($children instanceof ChildrenCollection && !$children->isInitialized()) {
                    $children->setLocale($locale);
                } elseif (!empty($children)) {
                    foreach ($children as $child) {
                        $this->cascadeDoLoadTranslation($child, $metadata->mappings[$fieldName], $locale);
                    }
                }
            }
        }

        if ($metadata->referenceMappings) {
            foreach ($metadata->referenceMappings as $fieldName) {
                $reference = $metadata->reflFields[$fieldName]->getValue($document);
                if ($reference instanceof ReferenceManyCollection && !$reference->isInitialized()) {
                    $reference->setLocale($locale);
                } else {
                    if ($reference instanceof \Traversable || is_array($reference)) {
                        foreach ($reference as $ref) {
                            $this->cascadeDoLoadTranslation($ref, $metadata->mappings[$fieldName], $locale);
                        }
                    } else {
                        $this->cascadeDoLoadTranslation($reference, $metadata->mappings[$fieldName], $locale);
                    }
                }
            }
        }

        if ($metadata->referrersMappings) {
            foreach ($metadata->referrersMappings as $fieldName) {
                $referrers = $metadata->reflFields[$fieldName]->getValue($document);
                if ($referrers instanceof ReferrersCollection && !$referrers->isInitialized()) {
                    $referrers->setLocale($locale);
                } elseif (!empty($referrers)) {
                    foreach ($referrers as $referrer) {
                        $this->cascadeDoLoadTranslation($referrer, $metadata->mappings[$fieldName], $locale);
                    }
                }
            }
        }
    }

    private function cascadeDoLoadTranslation($document, $mapping, $locale)
    {
        if (!$document || !($mapping['cascade'] & ClassMetadata::CASCADE_TRANSLATION)) {
            return;
        }

        $class = $this->dm->getClassMetadata(get_class($document));
        if ($document instanceof Proxy && !$document->__isInitialized()) {
            $this->setLocale($document, $class, $locale);
        } elseif ($this->isDocumentTranslatable($class)
            && $this->getCurrentLocale($document, $class) !== $locale
        ) {
            try {
                $this->doLoadTranslation($document, $class, $locale, true);
            } catch (\Exception $e) {
            }
        }
    }

    public function removeTranslation($document, $locale)
    {
        $metadata = $this->dm->getClassMetadata(get_class($document));
        if (!$this->isDocumentTranslatable($metadata)) {
            return;
        }

        if (1 === count($this->getLocalesFor($document))) {
            throw new PHPCRException('The last translation of a translatable document may not be removed');
        }

        if ($document instanceof Proxy) {
            $document->__load();
        }

        $oid = spl_object_hash($document);
        $this->documentTranslations[$oid][$locale] = null;
        $this->setLocale($document, $metadata, null);
    }

    private function doRemoveAllTranslations($document, ClassMetadata $metadata)
    {
        if (!$this->isDocumentTranslatable($metadata)) {
            return;
        }

        $node = $this->session->getNode($this->getDocumentId($document));
        $strategy = $this->dm->getTranslationStrategy($metadata->translator);
        $strategy->removeAllTranslations($document, $node, $metadata);
    }

    private function setLocale($document, ClassMetadata $metadata, $locale)
    {
        if (!$this->isDocumentTranslatable($metadata)) {
            return;
        }

        $oid = spl_object_hash($document);
        if (empty($this->documentLocales[$oid])) {
            $this->documentLocales[$oid] = array('original' => $locale);
        }
        $this->documentLocales[$oid]['current'] = $locale;

        if ($metadata->localeMapping
            && (!$document instanceof Proxy || $document->__isInitialized())
        ) {
            $metadata->reflFields[$metadata->localeMapping]->setValue($document, $locale);
        }
    }

    /**
* Determine the current locale of a managed document.
*
* If the document is not translatable, null is returned.
*
* If the document is translatable and the locale is mapped onto a document
* field, the value of that field is returned. Otherwise the UnitOfWork
* information on locales for documents without a locale mapping is
* consulted.
*
* If nothing matches (for example when this is a detached document), the
* default locale of the LocaleChooserStrategy is returned.
*
* @param object $document the managed document to get the locale for
* @param ClassMetadata $metadata document metadata, optional
*
* @return string|null the current locale of $document or null if it is not translatable
*/
    public function getCurrentLocale($document, ClassMetadata $metadata = null)
    {
        if (null === $metadata) {
            $metadata = $this->dm->getClassMetadata(get_class($document));
        }
        if (!$this->isDocumentTranslatable($metadata)) {
            return null;
        }

        if ($metadata->localeMapping
            && (!$document instanceof Proxy || $document->__isInitialized())
        ) {
            $locale = $metadata->reflFields[$metadata->localeMapping]->getValue($document);
            if ($locale) {
                return $locale;
            }
        }

        $oid = spl_object_hash($document);
        if (isset($this->documentLocales[$oid]['current'])) {
            return $this->documentLocales[$oid]['current'];
        }

        return $this->dm->getLocaleChooserStrategy()->getLocale();
    }

    /**
* Determine whether this document is translatable.
*
* To be translatable, it needs a translation strategy and have at least
* one translated field.
*
* @param ClassMetadata $metadata the document meta data
*
* @return boolean
*/
    public function isDocumentTranslatable(ClassMetadata $metadata)
    {
        return !empty($metadata->translator)
            && is_string($metadata->translator)
            && count($metadata->translatableFields) !== 0;
    }

    private static function objToStr($obj, DocumentManager $dm = null)
    {
        $string = method_exists($obj, '__toString')
            ? (string) $obj
            : ClassUtils::getClass($obj).'@'.spl_object_hash($obj);

        if ($dm) {
            try {
                $id = $dm->getUnitOfWork()->determineDocumentId($obj);
                if (!$id) {
                    $id = 'unmanaged or new document without id';
                }
                $string .= " ($id)";
            } catch (\Exception $e) {
                $id = 'failed to determine id';
                $string .= " ($id)";
            }
        }

        return $string;
    }

    private function getFullVersionedNodePath($document)
    {
        $path = $this->getDocumentId($document);
        $metadata = $this->dm->getClassMetadata(get_class($document));
        if ($metadata->versionable !== 'full') {
            throw new InvalidArgumentException(sprintf("The document at '%s' is not full versionable", $path));
        }

        $node = $this->session->getNode($path);
        $node->addMixin('mix:versionable');

        return $path;
    }

    /**
* Set the mapped mixins.
*
* @param ClassMetadata $metadata
* @param NodeInterface $node
* @param object $document The document to update autogenerated fields.
*/
    private function setMixins(Mapping\ClassMetadata $metadata, NodeInterface $node, $document)
    {
        $repository = $this->session->getRepository();
        if ($metadata->versionable === 'full') {
            if ($repository->getDescriptor(RepositoryInterface::OPTION_VERSIONING_SUPPORTED)) {
                $node->addMixin('mix:versionable');
            } elseif ($repository->getDescriptor(RepositoryInterface::OPTION_SIMPLE_VERSIONING_SUPPORTED)) {
                $node->addMixin('mix:simpleVersionable');
            }
        } elseif ($metadata->versionable === 'simple'
            && $repository->getDescriptor(RepositoryInterface::OPTION_SIMPLE_VERSIONING_SUPPORTED)
        ) {
            $node->addMixin('mix:simpleVersionable');
        }

        if (!$node->isNodeType('mix:referenceable') && $metadata->referenceable) {
            $node->addMixin('mix:referenceable');
        }

        // manually set the uuid if it is not present yet, so we can assign it to documents
        if ($node->isNodeType('mix:referenceable') && !$node->hasProperty('jcr:uuid')) {

            $uuid = false;

            $uuidFieldName = $metadata->getUuidFieldName();
            if ($uuidFieldName) {
                $uuid = $metadata->getFieldValue($document, $uuidFieldName);
            }

            if (!$uuid) {
                $uuid = $this->generateUuid();
            }

            $node->setProperty('jcr:uuid', $uuid);

            if ($uuidFieldName && !$metadata->getFieldValue($document, $uuidFieldName)) {
                $metadata->setFieldValue($document, $uuidFieldName, $uuid);
            }
        }
    }

    /**
* @return string a universally unique id.
*/
    private function generateUuid()
    {
        // php 5.3 compatibility, no direct execution of this closure.
        $g = $this->uuidGenerator;

        // TODO do we need to check with the storage backend if the generated id really is unique?
        return $g();
    }


    /**
* Sets the fetch depth on the session if the PHPCR session instance supports it
* and returns the previous fetch depth value
*
* @param int|null $fetchDepth
*
* @return int previous fetch depth value
*/
    public function setFetchDepth($fetchDepth = null)
    {
        if (!$this->useFetchDepth) {
            return 0;
        }

        $oldFetchDepth = $this->session->getSessionOption($this->useFetchDepth);

        if (isset($fetchDepth)) {
            $this->session->setSessionOption($this->useFetchDepth, $fetchDepth);
        }

        return $oldFetchDepth;
    }

    /**
* Gets the currently scheduled document updates in this UnitOfWork.
*
* @return array
*/
    public function getScheduledUpdates()
    {
        return $this->scheduledUpdates;
    }

    /**
* Gets the currently scheduled document insertions in this UnitOfWork.
*
* @return array
*/
    public function getScheduledInserts()
    {
        return $this->scheduledInserts;
    }

    /**
* Gets the currently scheduled document moves in this UnitOfWork.
*
* @return array
*/
    public function getScheduledMoves()
    {
        return $this->scheduledMoves;
    }

    /**
* Gets the currently scheduled document reorders in this UnitOfWork.
*
* @return array
*/
    public function getScheduledReorders()
    {
        return $this->scheduledReorders;
    }

    /**
* Gets the currently scheduled document deletions in this UnitOfWork.
*
* @return array
*/
    public function getScheduledRemovals()
    {
        return $this->scheduledRemovals;
    }

    /**
* Process null values in an associative array so that they can be stored in phpcr.
*
* Stores keys and null fields in the node and returns the processed values
*
* @param NodeInterface $node the node where to store the assoc array
* @param array $mapping the field's mapping
* @param array $assoc the associative array
* @return array
*/
    protected function processAssoc(NodeInterface $node, array $mapping, array $assoc)
    {
        $isNull = function($item) {
            return null === $item;
        };

        $isNotNull = function($item) {
            return null !== $item;
        };

        $keys = array_keys($assoc);
        $values = array_values(array_filter($assoc, $isNotNull));
        $nulls = array_keys(array_filter($assoc, $isNull));

        $node->setProperty($mapping['assoc'], $keys, PropertyType::STRING);
        $node->setProperty($mapping['assocNulls'], $nulls, PropertyType::STRING);
        return $values;
    }

    /**
* Create an associative array form the properties stored with the node
*
* @param array $properties the node's properties
* @param array $mapping the field's mapping information
* @return array
*/
    protected function createAssoc(array $properties, array $mapping)
    {
        $keys = $properties[$mapping['assoc']];
        $values = $properties[$mapping['property']];
        $nulls = isset($properties[$mapping['assocNulls']]) ? $properties[$mapping['assocNulls']] : array();

        // make sure we start with first value
        reset($values);
        $result = array();
        foreach ($keys as $key) {
            if (in_array($key, $nulls)) {
                $result[$key] = null;
            } else {
                $result[$key] = current($values);
                next($values);
            }
        }
        return $result;
    }

}
Something went wrong with that request. Please try again.