Snippets

Andrew Stark Bad User Architecture

Created by Andrew Stark
   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
<?php

declare(strict_types=1);

namespace App\Entity\User;

use App\Entity\Billing;
use App\Entity\Favorite;
use App\Entity\MailSubscriptionNewProfiles;
use App\Entity\Message;
use App\Entity\Notification\Notification;
use App\Entity\Premium;
use App\Entity\Pro6PP\Postcode;
use App\Entity\Review;
use App\Entity\SiteReview;
use App\Manager\User\UserImageManager;
use App\Traits\PropertiesToArrayTrait;
use App\Traits\UserTypeTrait;
use App\Validator\Constraints as CustomAssert;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use FOS\MessageBundle\Model\ParticipantInterface;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Class User.
 *
 * @ORM\Table(name="`user`", indexes={
 *     @ORM\Index(name="user_email_idx", columns={"email"}),
 *     @ORM\Index(name="user_slug_idx", columns={"slug"}),
 *     @ORM\Index(name="user_status_idx", columns={"status"}),
 *     @ORM\Index(name="user_cityslug_idx", columns={"city_slug"}),
 * }
 * )
 *
 * @ORM\Entity
 *
 * @UniqueEntity(fields={"email"}, groups={"registration"}, message="Dit e-mailadres is al bekend bij ons")
 *
 * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false)
 */
class User implements TimeStampableInterface, ParticipantInterface, UserInterface, \Serializable, AuditLoggableInterface
{
    use TimestampableTrait;
    use PropertiesToArrayTrait;
    use UserTypeTrait;
    use ToStringTrait;
    use AuditLoggableTrait;

    /**
     * @see Type entity
     */
    public const USER_TYPE_BABYSITTER          = 1;
    public const USER_TYPE_PARENT              = 2;
    public const USER_TYPE_GUEST_PARENT        = 3;
    public const USER_TYPE_GUEST_PARENT_BUREAU = 4;

    /**
     * List with available named types.
     *
     * @var string[]
     */
    public const USER_TYPES = [
        self::USER_TYPE_BABYSITTER          => 'Babysitter',
        self::USER_TYPE_PARENT              => 'UserParent',
        self::USER_TYPE_GUEST_PARENT        => 'Guest UserParent',
        self::USER_TYPE_GUEST_PARENT_BUREAU => 'Guest UserParent Bureau',
    ];

    /**
     * User status.
     */
    public const STATUS_DELETED           = -1; // user has been deleted, user can re-use email
    public const STATUS_INACTIVE          = 0;  // user has been blocked, user cannot re-use email
    public const STATUS_ACTIVE            = 2;  // user is active
    public const STATUS_INVISIBLE         = 3;  // user can still use all function but his profile is invisible
    public const STATUS_SUSPENDED         = 4;  // user is active, his profile is invisible, this status can be set only by admin
    public const STATUS_DELETED_FULFILLED = 5;  // user is pre deleted his account is fulfilled, user can re-use email (he cannot log in with old email)

    /**
     * List of statuses and there names.
     */
    public const STATUSES = [
        self::STATUS_DELETED           => 'Deleted',
        self::STATUS_INACTIVE          => 'Inactive',
        self::STATUS_ACTIVE            => 'Active',
        self::STATUS_INVISIBLE         => 'Invisible',
        self::STATUS_SUSPENDED         => 'Suspended',
        self::STATUS_DELETED_FULFILLED => 'Deleted (Fulfilled)',
    ];

    /**
     * All available roles.
     */
    public const ROLE_PREMIUM = 'ROLE_PREMIUM';

    /**
     * Able to read messages.
     */
    public const ROLE_MESSAGE_READ = 'ROLE_MESSAGE_READ';

    /**
     * Able to reply to messages in an existing conversation.
     * You can only reply on messages if you did not start the conversation.
     *
     * When the your are the person who starts the conversation then you need the role ROLE_MESSAGE_START
     * to reply on messages.
     */
    public const ROLE_MESSAGE_REPLY = 'ROLE_MESSAGE_REPLY';

    /**
     * Able to start a new conversation.
     *
     * When the your are the person who starts the conversation then you need the role ROLE_MESSAGE_START
     * to reply on messages.
     */
    public const ROLE_MESSAGE_START = 'ROLE_MESSAGE_START';

    /**
     * List of all available user roles.
     *
     * @var string[]
     */
    protected $availableUserRoles = [
        AdminUserInterface::ROLE_USER,
        self::ROLE_PREMIUM,
        self::ROLE_MESSAGE_READ,
        self::ROLE_MESSAGE_REPLY,
        self::ROLE_MESSAGE_START,
    ];

    /**
     * One User has Many favorites.
     *
     * @var Favorite[]
     *
     * @ORM\OneToMany(targetEntity="App\Entity\Favorite", mappedBy="userCreated", cascade={"remove"})
     */
    private $favoritesCreated;

    /**
     * One User is favorite Many.
     *
     * @var ArrayCollection|Favorite[]
     *
     * @ORM\OneToMany(targetEntity="App\Entity\Favorite", mappedBy="userReceived", cascade={"remove"})
     */
    private $favoritesReceived;

    /**
     * One User has Many reviews.
     *
     * @var ArrayCollection|Review[]
     *
     * @ORM\OneToMany(targetEntity="App\Entity\Review", mappedBy="userCreated", cascade={"remove"})
     * @ORM\OrderBy({"createdAt": "DESC"})
     */
    private $reviewsCreated;

    /**
     * One User has Many reviews.
     *
     * @var ArrayCollection|Review
     *
     * @ORM\OneToMany(targetEntity="App\Entity\Review", mappedBy="userReceived", cascade={"remove"})
     * @ORM\OrderBy({"createdAt": "DESC"})
     */
    private $reviewsReceived;

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer", unique=true)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="slug", type="string", length=255, unique=true)
     */
    private $slug;

    /**
     * @var string email of the user
     *
     * @ORM\Column(name="email", type="string", length=255, unique=true)
     *
     * @Assert\NotBlank(groups={"registration"})
     * @Assert\Length(
     *     min=4,
     *     max=255,
     *     groups={"Default", "registration"}
     * )
     * @Assert\Email(groups={"Default", "registration"}, mode="strict")
     */
    private $email;

    /**
     * @var string
     *
     * @Assert\NotBlank(groups={"registration"})
     * @Assert\Type(type="string")
     * @Assert\Length(
     *     min=4,
     *     max=255,
     *     groups={"registration"}
     * )
     */
    private $plainPassword;

    /**
     * @var string encrypted password
     *
     * @ORM\Column(name="password", type="string", length=72)
     */
    private $password;

    /**
     * @var Postcode postcode
     *
     * @ORM\ManyToOne(targetEntity="App\Entity\Pro6PP\Postcode")
     * @ORM\JoinColumn(name="postcode", referencedColumnName="postcode", nullable=false)
     *
     * @Assert\NotBlank(groups={"Default", "registration"})
     * @Assert\Length(
     *     min=6,
     *     max=7,
     *     groups={"Default", "registration"}
     * )
     * @CustomAssert\Postcode(groups={"Default", "registration"})
     */
    private $postcode;

    /**
     * @var string|null street
     *
     * @ORM\Column(name="street", type="string", length=255, nullable=true)
     */
    private $street;

    /**
     * @var int|null house number
     *
     * @ORM\Column(name="house_number", type="integer", nullable=true)
     *
     * @Assert\Type(type="integer")
     */
    private $houseNumber;

    /**
     * @var string|null house extension
     *
     * @ORM\Column(name="house_number_extension", type="string", length=20, nullable=true)
     *
     * @Assert\Length(max=20)
     */
    private $houseNumberExtension;

    /**
     * @var string city
     *
     * @ORM\Column(name="city", type="string", length=100)
     */
    private $city;

    /**
     * @var string city
     *
     * @ORM\Column(name="city_unique", type="string", length=100)
     */
    private $cityUnique;

    /**
     * @var string city
     *
     * @ORM\Column(name="city_slug", type="string", length=100)
     */
    private $citySlug;

    /**
     * @var string|null phone number
     *
     * @ORM\Column(name="phone_number", type="string", nullable=true)
     *
     * @Assert\Type(type="string")
     * @Assert\Length(
     *     min=10,
     *     max=13
     * )
     */
    private $phoneNumber;

    /**
     * @var int|null
     *
     * @ORM\Column(name="phone_verification_code", type="integer", nullable=true)
     */
    private $phoneVerificationCode;

    /**
     * @var bool
     *
     * @ORM\Column(name="phone_number_verified", type="boolean", options={"default": false})
     */
    private $phoneNumberVerified = false;

    /**
     * @var \DateTime|null
     *
     * @ORM\Column(name="last_phone_verify_code_requested_at", type="datetime", nullable=true)
     */
    private $lastPhoneVerifyCodeRequestedAt;

    /**
     * @var int how many times user requested phone number verification sms codes since first
     *
     * @ORM\Column(name="nr_of_verify_code_requests", type="integer", options={"default": 0})
     */
    private $nrOfVerifyCodeRequests = 0;

    /**
     * @var string|null facebook id
     *
     * @ORM\Column(name="facebook_id", type="string", length=255, nullable=true)
     */
    private $facebookId;

    /**
     * @var string|null google id
     *
     * @ORM\Column(name="google_id", type="string", length=255, nullable=true)
     */
    private $googleId;

    /**
     * @var string|null description
     *
     * @ORM\Column(name="description", type="text", nullable=true)
     *
     * @Assert\Type(type="string")
     * @Assert\Length(
     *     min=10,
     *     max=1500
     * )
     */
    private $description;

    /**
     * @var string|null
     */
    private $strippedDescription;

    /**
     * One User has Many images.
     *
     * @var ArrayCollection|ProfileImage[]
     *
     * @ORM\OneToMany(targetEntity="ProfileImage", mappedBy="owner", cascade={"remove"})
     * @ORM\OrderBy({"isAvatar": "DESC"})
     */
    private $images;

    /**
     * @var \DateTime when was the last login from the user
     *
     * @ORM\Column(name="last_login_at", type="datetime")
     */
    private $lastLogin;

    /**
     * @var int number of user login's
     *
     * @ORM\Column(name="nr_of_logins", type="integer")
     */
    private $nrOfLogins = 0;

    /**
     * @var \DateTime when the user profile was updated, we set profile updated at manually
     *
     * @ORM\Column(name="profile_updated_at", type="datetime")
     */
    private $profileUpdatedAt;

    /**
     * @var \DateTime|null
     *
     * @ORM\Column(name="deleted_at", type="datetime", nullable=true)
     */
    private $deletedAt;

    /**
     * @var string|null
     *
     * @ORM\Column(name="deleted_reason", type="text", nullable=true)
     */
    private $deletedReason;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="last_activity_at", type="datetime")
     */
    private $lastActivityAt;

    /**
     * @var string|null
     *
     * @Gedmo\IpTraceable(on="create")
     *
     * @ORM\Column(name="created_from_ip", type="string", length=45, nullable=true)
     */
    private $createdFromIp;

    /**
     * @var string|null
     *
     * @Gedmo\IpTraceable(on="update")
     *
     * @ORM\Column(name="updated_from_ip", type="string", length=45, nullable=true)
     */
    private $updatedFromIp;

    /**
     * @var int
     *
     * @ORM\Column(name="status", type="smallint")
     */
    private $status = 1;

    /**
     * Score based on profile completeness between 0 and 100%.
     *
     * @var int
     *
     * @ORM\Column(name="profile_score", type="integer")
     */
    private $profileScore = 0;

    /**
     * Holds UTM fields like: source-medium.
     *
     * @var string|null
     *
     * @ORM\Column(name="utm", type="string", length=64, nullable=true)
     */
    private $utm;

    /**
     * Mute in and out coming messages (alternative way of blocking a person that sends inappropriate messages)
     * When true, only messages the person has sent will be shown, the other side will be muted.
     * If the thread consist messages from one person, the other person does not see this thread.
     *
     * e.g.: Ruud = muted, Alice = victim
     * Ruud sends a message to Alice.
     * Ruud see the thread with his message
     * Alice does not see anything.
     *
     * When Alice starts sending messages to Ruud, then:
     * Ruud sees only his own messages that he sent to Alice
     * Alice sees only messages that she has sent to Ruud
     *
     * @var bool
     *
     * @ORM\Column(name="mute_messages", type="boolean", options={"default": false})
     */
    private $muteMessages = false;

    /**
     * @var mixed[]
     *
     * @ORM\Column(type="json_array")
     */
    private $roles = [];

    /**
     * @var Type|null
     *
     * @ORM\ManyToOne(targetEntity="Type", inversedBy="users")
     * @ORM\JoinColumn(name="user_type_id", referencedColumnName="id", nullable=false)
     *
     * @Assert\NotBlank
     */
    private $userType;

    /**
     * @var Babysitter|null
     *
     * @ORM\OneToOne(targetEntity="Babysitter", cascade={"persist"})
     * @ORM\JoinColumn(name="babysitter_id", referencedColumnName="id", nullable=true)
     *
     * @Assert\Type(type="App\Entity\User\Babysitter")
     * @Assert\Valid
     */
    private $userBabysitter;

    /**
     * @var UserParent|null
     *
     * @ORM\OneToOne(targetEntity="UserParent", cascade={"persist"})
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
     *
     * @Assert\Type(type="App\Entity\User\UserParent")
     * @Assert\Valid
     */
    private $userParent;

    /**
     * @var GuestParent|null
     *
     * @ORM\OneToOne(targetEntity="GuestParent", cascade={"persist"})
     * @ORM\JoinColumn(name="guest_parent_id", referencedColumnName="id", nullable=true)
     *
     * @Assert\Type(type="App\Entity\User\GuestParent")
     * @Assert\Valid
     */
    private $userGuestParent;

    /**
     * @var GuestParentBureau|null
     *
     * @ORM\OneToOne(targetEntity="GuestParentBureau", cascade={"persist"})
     * @ORM\JoinColumn(name="guest_parent_bureau_id", referencedColumnName="id", nullable=true)
     *
     * @Assert\Type(type="App\Entity\User\GuestParentBureau")
     * @Assert\Valid
     */
    private $userGuestParentBureau;

    /**
     * @var int
     *
     * @ORM\Column(name="avg_review_rating", type="float", options={"default": 0})
     */
    private $avgReviewRating = 0;

    /**
     * Total reviews received.
     *
     * @var int
     *
     * @ORM\Column(name="num_of_reviews", type="integer", options={"default": 0})
     */
    private $numOfReviews = 0;

    /**
     * Contains calculated distance.
     *
     * @var int
     *
     * @see SearchController->searchAction()
     */
    private $distance;

    /**
     * OneToOne workaround!
     * https://github.com/doctrine/doctrine2/pull/970#issuecomment-127687347.
     *
     * @ORM\OneToMany(targetEntity="App\Entity\MailSubscriptionNewProfiles", mappedBy="user")
     */
    private $mailSubscriptionNewProfiles;

    /**
     * @var SiteReview
     *
     * OneToOne workaround!
     * https://github.com/doctrine/doctrine2/pull/970#issuecomment-127687347
     *
     * @ORM\OneToMany(targetEntity="App\Entity\SiteReview", mappedBy="owner", cascade={"persist"})
     */
    private $siteReview;

    /**
     * @var \DateTime|null
     *
     * @ORM\Column(name="fulfilled_at", type="datetime", nullable=true)
     */
    private $fulfilledAt;

    /**
     * When true, user data is shared with partners via xml export.
     *
     * @var bool
     *
     * @ORM\Column(name="privacy_sharing_agreement", type="boolean", options={"default": true})
     */
    private $privacySharingAgreement = true;

    /**
     * @var bool
     *
     * @ORM\Column(name="email_verified", type="boolean", options={"default": false})
     */
    private $emailVerified = false;

    /**
     * @var Billing|null
     *
     * OneToOne workaround!
     * https://github.com/doctrine/doctrine2/pull/970#issuecomment-127687347
     *
     * @ORM\OneToMany(targetEntity="App\Entity\Billing", mappedBy="user")
     */
    private $billing;

    /**
     * @var Premium|null
     *
     * OneToOne workaround!
     * https://github.com/doctrine/doctrine2/pull/970#issuecomment-127687347
     *
     * @ORM\OneToMany(targetEntity="App\Entity\Premium", mappedBy="user")
     */
    private $premium;

    /**
     * @var string|null
     *
     * @ORM\Column(name="iban", type="string", length=34, nullable=true)
     */
    private $iban;

    /**
     * @var string|null
     *
     * @ORM\Column(name="first_name", type="string", length=35, nullable=true)
     *
     * @Assert\NotBlank(groups={"premium", "validateFirstName"})
     * @Assert\Length(
     *     min=2,
     *     max=35,
     *     groups={"premium", "validateFirstName"}
     * )
     * @CustomAssert\Name(groups={"premium", "validateFirstName"})
     */
    private $firstName;

    /**
     * @var string|null
     *
     * @ORM\Column(name="last_name", type="string", length=64, nullable=true)
     *
     * @Assert\NotBlank(groups={"premium", "validateLastName"})
     * @Assert\Length(
     *     min=2,
     *     max=64,
     * groups={"premium", "validateLastName"})
     * )
     * @CustomAssert\Name(groups={"premium", "validateLastName"}))
     */
    private $lastName;

    /**
     * @var ArrayCollection|Notification[]
     *
     * @ORM\OneToMany(targetEntity="App\Entity\Notification\Notification", mappedBy="user", cascade={"remove", "persist"})
     * @ORM\OrderBy({"createdAt": "DESC"})
     */
    private $notifications;

    /**
     * @var \FOS\MessageBundle\Model\ParticipantInterface
     *
     * @ORM\OneToMany(targetEntity="App\Entity\Message", mappedBy="sender")
     */
    protected $messages;

    /**
     * User constructor.
     */
    public function __construct()
    {
        $this->id                          = 0;
        $this->favoritesCreated            = new ArrayCollection();
        $this->favoritesReceived           = new ArrayCollection();
        $this->reviewsCreated              = new ArrayCollection();
        $this->images                      = new ArrayCollection();
        $this->notifications               = new ArrayCollection();
        $this->reviewsReceived             = new ArrayCollection();
        $this->lastLogin                   = new \DateTime('now');
        $this->lastActivityAt              = new \DateTime('now');
        $this->mailSubscriptionNewProfiles = new ArrayCollection();
        $this->siteReview                  = new ArrayCollection();
        $this->billing                     = new ArrayCollection();
        $this->premium                     = new ArrayCollection();
        $this->messages                    = new ArrayCollection();

        // Add default user roles
        $this->addRole(AdminUserInterface::ROLE_USER);
        $this->addRole(self::ROLE_MESSAGE_READ);
        $this->addRole(self::ROLE_MESSAGE_REPLY);
    }

    /**
     * @return string serialized string
     */
    public function serialize(): string
    {
        return serialize(
            [
                $this->id,
                $this->email,
                $this->password,
                $this->status,
                $this->roles,
            ]
        );
    }

    /**
     * @param string $serialized serialized string
     *
     * @see \Serializable::unserialize()
     */
    public function unserialize($serialized): void
    {
        list(
            $this->id,
            $this->email,
            $this->password,
            $this->status,
            $this->roles
            )
            = unserialize($serialized);
    }

    /**
     * @return string|null
     */
    public function getCreatedFromIp(): ?string
    {
        return $this->createdFromIp;
    }

    /**
     * Set createdFromIp.
     *
     * @param string $createdFromIp
     *
     * @return self
     */
    public function setCreatedFromIp(string $createdFromIp): self
    {
        $this->createdFromIp = $createdFromIp;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getUpdatedFromIp(): ?string
    {
        return $this->updatedFromIp;
    }

    /**
     * @param string $ip
     *
     * @return self
     */
    public function setUpdatedFromIp(string $ip): self
    {
        $this->updatedFromIp = $ip;

        return $this;
    }

    /**
     * Get email.
     *
     * @fixme not correct type
     *
     * @return string|null
     */
    public function getEmail(): ?string
    {
        return $this->email;
    }

    /**
     * Set email.
     *
     * @param string $email
     *
     * @return self
     */
    public function setEmail(string $email): self
    {
        $this->email = mb_strtolower($email);

        return $this;
    }

    /**
     * Get username.
     *
     * @return string email
     */
    public function getUsername(): string
    {
        return $this->email;
    }

    /**
     * @return string
     */
    public function getPlainPassword(): ?string
    {
        return $this->plainPassword;
    }

    /**
     * @param string $password
     *
     * @return self
     */
    public function setPlainPassword(string $password): self
    {
        $this->plainPassword = $password;

        return $this;
    }

    /**
     * Get password.
     *
     * @return string
     */
    public function getPassword(): string
    {
        return $this->password;
    }

    /**
     * Set password.
     *
     * @param string $password
     *
     * @return self
     */
    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * [updatePostcodeRelatedFields description].
     *
     * @return self
     */
    public function updatePostcodeRelatedFields(): self
    {
        $city = $this->postcode->getCity();

        $this->city       = $city->getName();
        $this->cityUnique = $city->getUniqueName();
        $this->citySlug   = $city->getSlug();

        return $this;
    }

    /**
     * Get postcode.
     *
     * @return Postcode
     */
    public function getPostcode(): ?Postcode
    {
        return $this->postcode;
    }

    /**
     * Set postcode.
     *
     * @param Postcode $postcode
     *
     * @return self
     */
    public function setPostcode(Postcode $postcode = null): self
    {
        $this->postcode = $postcode;

        return $this;
    }

    /**
     * Get street.
     *
     * @return string|null
     */
    public function getStreet(): ?string
    {
        return $this->street;
    }

    /**
     * Get address.
     *
     * @return string|null
     */
    public function getAddress(): ?string
    {
        if (null === $this->street && null === $this->houseNumber) {
            return null;
        }

        $address = $this->street.' '.$this->houseNumber;

        if (null !== $this->houseNumberExtension) {
            $address .= ' '.$this->houseNumberExtension;
        }

        return $address;
    }

    /**
     * Set street.
     *
     * @param string|null $street
     *
     * @return self
     */
    public function setStreet(?string $street): self
    {
        $this->street = $street;

        return $this;
    }

    /**
     * Get city.
     *
     * @return string
     */
    public function getCity(): string
    {
        return $this->city;
    }

    /**
     * Set city.
     *
     * @param string $city
     *
     * @return self
     */
    public function setCity(string $city): self
    {
        $this->city = $city;

        return $this;
    }

    /**
     * Get city unique name.
     *
     * @return string
     */
    public function getCityUnique(): string
    {
        return $this->cityUnique;
    }

    /**
     * Set city unique name.
     *
     * @param string $cityUnique
     *
     * @return self
     */
    public function setCityUnique(string $cityUnique): self
    {
        $this->cityUnique = $cityUnique;

        return $this;
    }

    /**
     * Get city slug.
     *
     * @return string
     */
    public function getCitySlug(): string
    {
        return $this->citySlug;
    }

    /**
     * Set city slug.
     *
     * @param string $citySlug
     *
     * @return self
     */
    public function setCitySlug(string $citySlug): self
    {
        $this->citySlug = $citySlug;

        return $this;
    }

    /**
     * Get phoneNumber.
     *
     * @return string|null
     */
    public function getPhoneNumber(): ?string
    {
        return $this->phoneNumber;
    }

    /**
     * Set phoneNumber.
     *
     * @param string|null $phoneNumber
     *
     * @return self
     */
    public function setPhoneNumber(?string $phoneNumber): self
    {
        $this->phoneNumber = $phoneNumber;

        return $this;
    }

    /**
     * Does login logging.
     * Sets last login date and adds 1+ to login count.
     *
     * @throws \Exception
     *
     * @return self
     */
    public function addLogin(): self
    {
        $this->setLastLogin(new \DateTime());
        $this->setNrOfLogins($this->getNrOfLogins() + 1);

        return $this;
    }

    /**
     * Get lastLogin.
     *
     * @return \DateTime
     */
    public function getLastLogin(): \DateTime
    {
        return $this->lastLogin;
    }

    /**
     * Set lastLogin.
     *
     * @param \DateTime $lastLogin
     *
     * @return self
     */
    public function setLastLogin(\DateTime $lastLogin): self
    {
        $this->lastLogin = $lastLogin;

        return $this;
    }

    /**
     * Get lastLogin.
     *
     * @return int
     */
    public function getNrOfLogins(): int
    {
        return $this->nrOfLogins;
    }

    /**
     * Set lastLogin.
     *
     * @param int $nrOfLogins
     *
     * @return self
     */
    public function setNrOfLogins(int $nrOfLogins): self
    {
        $this->nrOfLogins = $nrOfLogins;

        return $this;
    }

    /**
     * Get getProfileUpdatedAt.
     *
     * @return \DateTime
     */
    public function getProfileUpdatedAt(): \DateTime
    {
        return $this->profileUpdatedAt;
    }

    /**
     * Set profileUpdatedAt.
     *
     * @param \DateTime $profileUpdatedAt
     *
     * @return self
     */
    public function setProfileUpdatedAt(\DateTime $profileUpdatedAt): self
    {
        $this->profileUpdatedAt = $profileUpdatedAt;

        return $this;
    }

    /**
     * @return \DateTime|null
     */
    public function getDeletedAt(): ?\DateTime
    {
        return $this->deletedAt;
    }

    /**
     * @param \DateTime|null $deletedAt
     *
     * @return self
     */
    public function setDeletedAt(?\DateTime $deletedAt): self
    {
        $this->deletedAt = $deletedAt;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getDeletedReason(): ?string
    {
        return $this->deletedReason;
    }

    /**
     * @param string|null $deletedReason
     *
     * @return self
     */
    public function setDeletedReason(?string $deletedReason): self
    {
        $this->deletedReason = $deletedReason;

        return $this;
    }

    /**
     * @return \DateTime
     */
    public function getLastActivityAt(): \DateTime
    {
        return $this->lastActivityAt;
    }

    /**
     * @param \DateTime $lastActivityAt
     *
     * @return self
     */
    public function setLastActivityAt(\DateTime $lastActivityAt): self
    {
        $this->lastActivityAt = $lastActivityAt;

        return $this;
    }

    /**
     * Get status.
     *
     * @return int
     */
    public function getStatus(): int
    {
        return $this->status;
    }

    /**
     * Set status.
     *
     * @param int $status
     *
     * @return self
     */
    public function setStatus(int $status): self
    {
        if (false === isset(self::STATUSES[$status])) {
            throw new \InvalidArgumentException(sprintf('Invalid status given: %d', $status));
        }

        $this->status = $status;

        return $this;
    }

    /**
     * isStatusSuspended.
     *
     * @return bool
     */
    public function isStatusSuspended(): bool
    {
        return self::STATUS_SUSPENDED === $this->status;
    }

    /**
     * isStatusDeleted.
     *
     * @return bool
     */
    public function isStatusDeleted(): bool
    {
        return self::STATUS_DELETED === $this->status;
    }

    /**
     * isStatusInactive.
     *
     * @return bool
     */
    public function isStatusInactive(): bool
    {
        return self::STATUS_INACTIVE === $this->status;
    }

    /**
     * isStatusActive.
     *
     * @return bool
     */
    public function isStatusActive(): bool
    {
        return self::STATUS_ACTIVE === $this->status;
    }

    /**
     * isStatusInvisible.
     *
     * @return bool
     */
    public function isStatusInvisible(): bool
    {
        return self::STATUS_INVISIBLE === $this->status;
    }

    /**
     * isStatusDeletedFulfilled.
     *
     * @return bool
     */
    public function isStatusDeletedFulfilled(): bool
    {
        return self::STATUS_DELETED_FULFILLED === $this->status;
    }

    /**
     * @return int
     */
    public function getProfileScore(): int
    {
        return $this->profileScore;
    }

    /**
     * @param int $score
     *
     * @return self
     */
    public function setProfileScore(int $score): self
    {
        $this->profileScore = $score;

        return $this;
    }

    /**
     * Get UTM.
     *
     * @return string|null
     */
    public function getUtm(): ?string
    {
        return $this->utm;
    }

    /**
     * Set UTM.
     *
     * @param string|null $utm
     *
     * @return self
     */
    public function setUtm(?string $utm): self
    {
        $this->utm = $utm;

        return $this;
    }

    /**
     * @param bool $muteMessages
     *
     * @return self
     */
    public function setMuted(bool $muteMessages): self
    {
        $this->muteMessages = $muteMessages;

        return $this;
    }

    /**
     * Get slug.
     *
     * @return string
     */
    public function getSlug(): string
    {
        return $this->slug;
    }

    /**
     * Set slug.
     *
     * @param string $slug
     *
     * @return self
     */
    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

    /**
     * Get houseNumber.
     *
     * @return int|null
     */
    public function getHouseNumber(): ?int
    {
        return $this->houseNumber;
    }

    /**
     * Set houseNumber.
     *
     * @param int|null $houseNumber
     *
     * @return self
     */
    public function setHouseNumber(?int $houseNumber): self
    {
        $this->houseNumber = $houseNumber;

        // also clear street
        if (null === $houseNumber) {
            $this->street = null;
        }

        return $this;
    }

    /**
     * Get houseNumberExtension.
     *
     * @return string|null
     */
    public function getHouseNumberExtension(): ?string
    {
        return $this->houseNumberExtension;
    }

    /**
     * Set houseNumberExtension.
     *
     * @param string|null $houseNumberExtension
     *
     * @return self
     */
    public function setHouseNumberExtension(?string $houseNumberExtension): self
    {
        $this->houseNumberExtension = $houseNumberExtension;

        return $this;
    }

    /**
     * Add favoritesCreated.
     *
     * @param Favorite $favoritesCreated
     *
     * @return self
     */
    public function addFavoritesCreated(Favorite $favoritesCreated): self
    {
        $this->favoritesCreated[] = $favoritesCreated;

        return $this;
    }

    /**
     * Check if given user is a favorite.
     *
     * @param self $user
     *
     * @return bool
     */
    public function isFavorite(self $user): bool
    {
        foreach ($this->getFavoritesCreated() as $favorite) {
            if ($favorite->getUserReceived()->getId() === $user->getId()) {
                return true;
            }
        }

        return false;
    }

    /**
     * Get favoritesCreated.
     *
     * @return Collection|Favorite[]
     */
    public function getFavoritesCreated(): Collection
    {
        return $this->favoritesCreated;
    }

    /**
     * Get id.
     *
     * @return int
     */
    public function getId(): int
    {
        return $this->id;
    }

    /**
     * Check if a user can add an other user as favorite.
     *
     * @param self $user
     *
     * @return bool true if can add as favorite, false otherwise
     */
    public function canFavorite(self $user): bool
    {
        return $this->canContact($user);
    }

    /**
     * @param self $user
     *
     * @return bool
     */
    public function hasConversationWithUser(self $user): bool
    {
        $hasConversation = false;
        // check if at least one message exists between users
        $this->messages->filter(
            function (Message $message) use ($user, &$hasConversation): void {
                foreach ($message->getThread()->getParticipants() as $participant) {
                    if ($user->getId() === $participant->getId()) {
                        $hasConversation = true;
                        break;
                    }
                }
            }
        );

        return $hasConversation;
    }

    /**
     * Check if this user can contact given user.
     *
     * @param self $user
     *
     * @return bool
     */
    public function canContact(self $user): bool
    {
        // it is not possible to contact with yourself
        if ($this->getId() === $user->getId()) {
            return false;
        }

        // it is not possible to contact user that is not active but is not status invisible
        if (false === $user->isStatusActive() && false === $user->isStatusInvisible()) {
            return false;
        }

        // it is not possible to contact user that is muted
        if (true === $user->isMuted()) {
            return false;
        }

        // can not contact fulfilled user if has no conversation
        if (true === $user->isFulfilled() && false === $this->hasConversationWithUser($user)) {
            return false;
        }

        $contactableUserTypes = $this->getContactableUserTypes();

        return \in_array($user->getUserType()->getId(), $contactableUserTypes, true);
    }

    /**
     * @return bool
     */
    public function isMuted(): bool
    {
        return $this->muteMessages;
    }

    /**
     * @return array
     */
    public function getContactableUserTypes(): array
    {
        return $this->getContactableUserTypesById($this->userType->getId());
    }

    /**
     * @return Type|null
     */
    public function getUserType(): ?Type
    {
        return $this->userType;
    }

    /**
     * @param Type $userType
     *
     * @return self
     */
    public function setUserType(Type $userType): self
    {
        $this->userType = $userType;

        return $this;
    }

    /**
     * Add favoritesReceived.
     *
     * @param Favorite $favoritesReceived
     *
     * @return self
     */
    public function addFavoritesReceived(Favorite $favoritesReceived): self
    {
        $this->favoritesReceived[] = $favoritesReceived;

        return $this;
    }

    /**
     * Get favoritesReceived.
     *
     * @return Collection|Favorite[]
     */
    public function getFavoritesReceived(): Collection
    {
        return $this->favoritesReceived;
    }

    /**
     * Add reviewsCreated.
     *
     * @param Review $reviewsCreated
     *
     * @return self
     */
    public function addReviewsCreated(Review $reviewsCreated): self
    {
        $this->reviewsCreated[] = $reviewsCreated;

        return $this;
    }

    /**
     * Get reviewsCreated.
     *
     * @return Collection|Review[]
     */
    public function getReviewsCreated(): Collection
    {
        return $this->reviewsCreated;
    }

    /**
     * Add reviewsReceived.
     *
     * @param Review $reviewsReceived
     *
     * @return self
     */
    public function addReviewsReceived(Review $reviewsReceived): self
    {
        $this->reviewsReceived[] = $reviewsReceived;

        return $this;
    }

    /**
     * Get reviewsReceived.
     *
     * @return Collection|Review[]
     */
    public function getReviewsReceived(): Collection
    {
        return $this->reviewsReceived;
    }

    /**
     * Return the age of the user.
     *
     * @return int|null age
     */
    public function getAge(): ?int
    {
        if (false === method_exists($this->getUserTypeProperties(), 'getDateOfBirth')) {
            return null;
        }

        /** @var \DateTime $dateOfBirth */
        $dateOfBirth = $this->getUserTypeProperties()->getDateOfBirth();
        if (null === $dateOfBirth) {
            return null;
        }

        $dateNow = new \DateTime('now');

        return $dateOfBirth->diff($dateNow)->y;
    }

    /**
     * Get the user type properties.
     *
     * @throws \RuntimeException
     *
     * @return Babysitter|GuestParent|GuestParentBureau|UserParent
     */
    public function getUserTypeProperties()
    {
        $userTypeProperties = null;

        switch ($this->getUserType()->getId()) {
            case self::USER_TYPE_BABYSITTER:
                $userTypeProperties = $this->getUserBabysitter();
                break;

            case self::USER_TYPE_PARENT:
                $userTypeProperties = $this->getUserParent();
                break;

            case self::USER_TYPE_GUEST_PARENT:
                $userTypeProperties = $this->getUserGuestParent();
                break;

            case self::USER_TYPE_GUEST_PARENT_BUREAU:
                $userTypeProperties = $this->getUserGuestParentBureau();
                break;
        }

        if (null === $userTypeProperties) {
            throw new \RuntimeException(sprintf('Unknown user type: %d', $this->getUserType()->getId()));
        }

        return $userTypeProperties;
    }

    /**
     * @return Babysitter|null
     */
    public function getUserBabysitter(): ?Babysitter
    {
        return $this->userBabysitter;
    }

    /**
     * @param Babysitter|null $userBabysitter
     *
     * @return self
     */
    public function setUserBabysitter(?Babysitter $userBabysitter): self
    {
        $this->userBabysitter = $userBabysitter;

        return $this;
    }

    /**
     * @return UserParent|null
     */
    public function getUserParent(): ?UserParent
    {
        return $this->userParent;
    }

    /**
     * @param UserParent|null $userParent
     *
     * @return self
     */
    public function setUserParent(?UserParent $userParent): self
    {
        $this->userParent = $userParent;

        return $this;
    }

    /**
     * @return GuestParent|null
     */
    public function getUserGuestParent(): ?GuestParent
    {
        return $this->userGuestParent;
    }

    /**
     * @param GuestParent|null $userGuestParent
     *
     * @return self
     */
    public function setUserGuestParent(?GuestParent $userGuestParent): self
    {
        $this->userGuestParent = $userGuestParent;

        return $this;
    }

    /**
     * @return GuestParentBureau|null
     */
    public function getUserGuestParentBureau(): ?GuestParentBureau
    {
        return $this->userGuestParentBureau;
    }

    /**
     * @param GuestParentBureau|null $userGuestParentBureau
     *
     * @return self
     */
    public function setUserGuestParentBureau(?GuestParentBureau $userGuestParentBureau): self
    {
        $this->userGuestParentBureau = $userGuestParentBureau;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getDescription(): ?string
    {
        return $this->description;
    }

    /**
     * @param string|null $description
     *
     * @return self
     */
    public function setDescription(?string $description): self
    {
        $this->description = $description;

        // reset so it gets recalculated
        $this->strippedDescription = null;

        return $this;
    }

    /**
     * Removes phone number, emails and websites.
     *
     * @return string|null
     */
    public function getStrippedDescription(): ?string
    {
        if (null === $this->description) {
            return null;
        }

        if (null !== $this->strippedDescription) {
            return $this->strippedDescription;
        }

        $email = $this->email;

        // whitelist with words that should not be replaced.
        $whitelist = ['live'];
        $replace   = [];

        // replace email
        $replace[] = $email; // info@vgwhousing.nl
        $domain1   = mb_substr($email, mb_strpos($email, '@')); // @vgwhousing.nl
        $domain2   = mb_substr($domain1, 0, mb_strrpos($domain1, '.')); // @vgwhousing
        $domain3   = str_replace('@', '', $domain2); // vgwhousing
        $replace[] = $domain1;
        $replace[] = $domain2;
        $replace[] = $domain3;

        // find everything that resembles an email address
        $description = $this->description;
        $words       = explode(' ', $description);
        foreach ($words as $k => $word) {
            if (false !== mb_strpos($word, '@')) {
                $replace[] = $word;

                $wordCleaned = preg_replace('/[^0-9a-z@]/', '', $word);

                $pos = mb_strpos($wordCleaned, '@');
                if (0 === $pos && $k > 0) {
                    // first letter is @ so remove previous word too
                    $replace[] = $words[$k - 1];
                }
                if (mb_strlen($wordCleaned) - 1 === $pos) {
                    // last letter is @ so remove next word too
                    $replace[] = $words[$k + 1];
                }
            }
        }

        // find everything that resembles a telephone number
        preg_match_all('/[0-9][0-9 ]{4,20}[0-9]/', $description, $matches);
        foreach ($matches[0] as $m) {
            $replace[] = $m;
        }

        // find anything that resembles an domainname
        preg_match_all(
            '/\b(\w*(\.com|\.org|\.nl|\.de|\.be|\.co\.uk)\w*)\b/',
            $description,
            $matches,
            PREG_PATTERN_ORDER
        );

        if (\count($matches[0]) > 0) {
            $matches = array_unique($matches[0]);
            foreach ($matches as $m) {
                $replace[] = $m;
            }
        }

        // get name
        $name = mb_strtolower($this->getName());

        // start replacing
        foreach ($replace as $v) {
            if (mb_strlen($v) < 3) {
                continue;
            }
            // BUGS-287, do not replace name
            if (mb_strtolower($v) === $name) {
                continue;
            }
            if (true === \in_array($v, $whitelist, true)) {
                continue;
            }

            // replace with ***
            $v           = str_replace('\\', '', $v);
            $v           = str_replace('/', '', $v);
            $description = preg_replace('/'.preg_quote($v).'/i', str_pad('', mb_strlen($v), '*'), $description);
            if (null === $description) {
                // restore backup
                $description = $this->description;
                break;
            }
        }

        // return a maximum of 8 '*'
        $this->strippedDescription = preg_replace('/\*{8,}/', '********', $description);

        return $this->strippedDescription;
    }

    /**
     * @return bool
     */
    public function isUserTypeBabysitter(): bool
    {
        return self::USER_TYPE_BABYSITTER === $this->getUserType()->getId();
    }

    /**
     * @return bool
     */
    public function isUserTypeParent(): bool
    {
        return self::USER_TYPE_PARENT === $this->getUserType()->getId();
    }

    /**
     * @return bool
     */
    public function isUserTypeGuestParent(): bool
    {
        return self::USER_TYPE_GUEST_PARENT === $this->getUserType()->getId();
    }

    /**
     * @return bool
     */
    public function isUserTypeGuestParentBureau(): bool
    {
        return self::USER_TYPE_GUEST_PARENT_BUREAU === $this->getUserType()->getId();
    }

    /**
     * Get the correct name based on user type.
     *
     * @return string name of user
     */
    public function getName(): string
    {
        if (self::USER_TYPE_GUEST_PARENT_BUREAU === $this->getUserType()->getId()) {
            return $this->getUserTypeProperties()->getCompanyName();
        }

        return $this->getFirstName();
    }

    /**
     * Get the first and last name of User.
     *
     * @return string|null name of user
     */
    public function getFullName(): ?string
    {
        $name = $this->getFirstName();
        if (null !== $this->getLastName()) {
            $name .= ' '.$this->getLastName();
        }

        return $name;
    }

    /**
     * @return int
     */
    public function getDistance(): int
    {
        return $this->distance;
    }

    /**
     * @param int $distance
     *
     * @return self
     */
    public function setDistance(int $distance): self
    {
        $this->distance = (int) $distance;

        return $this;
    }

    /**
     * @return MailSubscriptionNewProfiles|null
     */
    public function getMailSubscriptionNewProfiles(): ?MailSubscriptionNewProfiles
    {
        if (true === ($this->mailSubscriptionNewProfiles->first() instanceof MailSubscriptionNewProfiles)) {
            return $this->mailSubscriptionNewProfiles->first();
        }

        return null;
    }

    /**
     * @param MailSubscriptionNewProfiles|null $mailSubscriptionNewProfiles
     *
     * @return self
     */
    public function setMailSubscriptionNewProfiles(?MailSubscriptionNewProfiles $mailSubscriptionNewProfiles): self
    {
        $this->mailSubscriptionNewProfiles->clear();
        if (null !== $mailSubscriptionNewProfiles) {
            $this->mailSubscriptionNewProfiles->add($mailSubscriptionNewProfiles);
            $mailSubscriptionNewProfiles->setUser($this);
        }

        return $this;
    }

    /**
     * @return float
     */
    public function getAvgReviewRating(): float
    {
        return $this->avgReviewRating;
    }

    /**
     * @param float $avgReviewRating
     *
     * @return self
     */
    public function setAvgReviewRating(float $avgReviewRating): self
    {
        $this->avgReviewRating = $avgReviewRating;

        return $this;
    }

    /**
     * @return int
     */
    public function getNumOfReviews(): int
    {
        return $this->numOfReviews;
    }

    /**
     * @param int $numOfReviews
     *
     * @return self
     */
    public function setNumOfReviews(int $numOfReviews): self
    {
        $this->numOfReviews = $numOfReviews;

        return $this;
    }

    /**
     * @return bool
     */
    public function isMuteMessages(): bool
    {
        return $this->muteMessages;
    }

    /**
     * @return string|null
     */
    public function getSalt(): ?string
    {
        return null;
    }

    /**
     * @return bool
     */
    public function eraseCredentials(): bool
    {
        return false;
    }

    /**
     * @return bool
     */
    public function isEnabled(): bool
    {
        return
            self::STATUS_ACTIVE    === $this->status ||
            self::STATUS_INVISIBLE === $this->status ||
            self::STATUS_SUSPENDED === $this->status ||
            $this->hasRole(AdminUserInterface::ROLE_ADMIN);
    }

    /**
     * @return string[]
     */
    public function getRoles(): array
    {
        $roles = $this->roles;

        return array_unique($roles);
    }

    /**
     * Add role.
     *
     * @param string $role
     */
    public function addRole(string $role): void
    {
        $this->roles[] = $role;
        $this->roles   = array_unique($this->roles);
    }

    /**
     * Remove role.
     *
     * @param string $role
     *
     * @return bool true if role is remove, otherwise false
     */
    public function removeRole(string $role): bool
    {
        if (false !== ($key = array_search($role, $this->roles, true))) {
            unset($this->roles[$key]);

            return true;
        }

        return false;
    }

    /**
     * @param string[] $roles
     *
     * @return self
     */
    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * Check if User has role.
     *
     * @param string $role
     *
     * @return bool
     */
    public function hasRole(string $role): bool
    {
        return \in_array($role, $this->getRoles(), true);
    }

    /**
     * @return string[]
     */
    public function getAvailableUserRoles(): array
    {
        return $this->availableUserRoles;
    }

    /**
     * Check if user has logged in via social media.
     *
     * @return bool
     */
    public function hasSocialLogin(): bool
    {
        return !empty($this->getFacebookId() || !empty($this->getGoogleId()));
    }

    /**
     * Gets facebookId.
     *
     * @return string|null
     */
    public function getFacebookId(): ?string
    {
        return $this->facebookId;
    }

    /**
     * Sets facebookId.
     *
     * @param string|null $facebookId
     *
     * @return self
     */
    public function setFacebookId(?string $facebookId): self
    {
        $this->facebookId = $facebookId;

        return $this;
    }

    /**
     * Get google id.
     *
     * @return string|null
     */
    public function getGoogleId(): ?string
    {
        return $this->googleId;
    }

    /**
     * Set google id.
     *
     * @param string|null $googleId
     *
     * @return self
     */
    public function setGoogleId(?string $googleId): self
    {
        $this->googleId = $googleId;

        return $this;
    }

    /**
     * @return \DateTime|null
     */
    public function getFulfilledAt(): ?\DateTime
    {
        return $this->fulfilledAt;
    }

    /**
     * @param \DateTime|null $fulfilledAt
     *
     * @return self
     */
    public function setFulfilledAt(?\DateTime $fulfilledAt): self
    {
        $this->fulfilledAt = $fulfilledAt;

        return $this;
    }

    /**
     * Will return true when fulfilledAt is set.
     *
     * @return bool
     */
    public function isFulfilled(): bool
    {
        if (null === $this->fulfilledAt) {
            return false;
        }

        return true;
    }

    /**
     * @return int|null
     */
    public function getPhoneVerificationCode(): ?int
    {
        return $this->phoneVerificationCode;
    }

    /**
     * @param int|null $phoneVerificationCode
     *
     * @return self
     */
    public function setPhoneVerificationCode(?int $phoneVerificationCode): self
    {
        $this->phoneVerificationCode = $phoneVerificationCode;

        return $this;
    }

    /**
     * @return bool
     */
    public function isPhoneNumberVerified(): bool
    {
        return $this->phoneNumberVerified;
    }

    /**
     * @param bool $phoneNumberVerified
     *
     * @return self
     */
    public function setPhoneNumberVerified(bool $phoneNumberVerified): self
    {
        $this->phoneNumberVerified = $phoneNumberVerified;

        return $this;
    }

    /**
     * @return \DateTime|null
     */
    public function getLastPhoneVerifyCodeRequestedAt(): ?\DateTime
    {
        return $this->lastPhoneVerifyCodeRequestedAt;
    }

    /**
     * @param \DateTime|null $date
     *
     * @return self
     */
    public function setLastPhoneVerifyCodeRequestedAt(?\DateTime $date): self
    {
        $this->lastPhoneVerifyCodeRequestedAt = $date;

        return $this;
    }

    /**
     * @return int
     */
    public function getNrOfVerifyCodeRequests(): int
    {
        return $this->nrOfVerifyCodeRequests;
    }

    /**
     * @param int $nrOfVerifyCodeRequests
     *
     * @return self
     */
    public function setNrOfVerifyCodeRequests(int $nrOfVerifyCodeRequests): self
    {
        $this->nrOfVerifyCodeRequests = $nrOfVerifyCodeRequests;

        return $this;
    }

    /**
     * @return bool
     */
    public function isPrivacySharingAgreement(): bool
    {
        return $this->privacySharingAgreement;
    }

    /**
     * @param bool $privacySharingAgreement
     *
     * @return self
     */
    public function setPrivacySharingAgreement(bool $privacySharingAgreement): self
    {
        $this->privacySharingAgreement = $privacySharingAgreement;

        return $this;
    }

    /**
     * We clear and not show images which not exist on server. User images will be updated after some flush().
     *
     * @return ArrayCollection|ProfileImage[]
     */
    public function getImages()
    {
        return $this->images;
    }

    /**
     * @param ProfileImage $image
     *
     * @return self
     */
    public function addImage(ProfileImage $image): self
    {
        if (\count($this->images) >= UserImageManager::MAX_PROFILE_IMAGES) {
            // silently return
            return $this;
        }
        if ($this->images->contains($image)) {
            return $this;
        }

        $this->images->add($image);

        return $this;
    }

    /**
     * @param ProfileImage $image
     *
     * @return self
     */
    public function removeImage(ProfileImage $image): self
    {
        if ($this->images->contains($image)) {
            $this->images->removeElement($image);
        }

        return $this;
    }

    /**
     * @return ProfileImage|null
     */
    public function getProfileAvatar(): ?ProfileImage
    {
        foreach ($this->images as $image) {
            if ($image->isAvatar()) {
                return $image;
            }
        }

        return null;
    }

    /**
     * @return string
     */
    public function getProfileImageUrl(): string
    {
        foreach ($this->images as $image) {
            if ($image->isAvatar()) {
                return $image->getImagePath();
            }
        }

        return '/img/no-image.png';
    }

    /**
     * @return SiteReview|null
     */
    public function getSiteReview(): ?SiteReview
    {
        if (true === ($this->siteReview->last() instanceof SiteReview)) {
            return $this->siteReview->last();
        }

        return null;
    }

    /**
     * @param SiteReview $siteReview
     */
    public function setSiteReview(SiteReview $siteReview): void
    {
        $this->siteReview->clear();
        $this->siteReview->add($siteReview);
        $siteReview->setOwner($this);
    }

    /**
     * @return bool
     */
    public function isEmailVerified(): bool
    {
        return $this->emailVerified;
    }

    /**
     * @param bool $boolean
     *
     * @return self
     */
    public function setIsEmailVerified(bool $boolean): self
    {
        $this->emailVerified = $boolean;

        return $this;
    }

    /**
     * get Billing.
     *
     * @return Billing|null
     */
    public function getBilling(): ?Billing
    {
        if (true === ($this->billing->last() instanceof Billing)) {
            return $this->billing->last();
        }

        return null;
    }

    /**
     * @param Billing|null $billing
     *
     * @return self
     */
    public function setBilling(?Billing $billing): self
    {
        $this->billing->clear();
        if (null !== $billing) {
            $this->billing->add($billing);
        }

        return $this;
    }

    /**
     * get Premium.
     *
     * @return Premium|null
     */
    public function getPremium(): ?Premium
    {
        if (true === ($this->premium->last() instanceof Premium)) {
            return $this->premium->last();
        }

        return null;
    }

    /**
     * @param Premium|null $premium
     *
     * @return self
     */
    public function setPremium(?Premium $premium): self
    {
        $this->premium->clear();
        if (null !== $premium) {
            $this->premium->add($premium);
        }

        return $this;
    }

    /**
     * get Iban.
     *
     * @return string|null
     */
    public function getIban(): ?string
    {
        return $this->iban;
    }

    /**
     * Set Iban.
     *
     * @param string|null $iban
     *
     * @return self
     */
    public function setIban(?string $iban): self
    {
        if (true === \is_string($iban)) {
            // TODO move to DTO and fix this spripping spaces in mapper
            $iban = preg_replace('/\s/', '', $iban);
        }

        $this->iban = $iban;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getFirstName(): ?string
    {
        return $this->firstName;
    }

    /**
     * @param string|null $firstName
     *
     * @return self
     */
    public function setFirstName(?string $firstName): self
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getLastName(): ?string
    {
        return $this->lastName;
    }

    /**
     * @param string|null $lastName
     *
     * @return self
     */
    public function setLastName(?string $lastName): self
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * @return ArrayCollection|Notification[]
     */
    public function getNotifications(): Collection
    {
        return $this->notifications;
    }

    /**
     * @param Notification $entity
     *
     * @return self
     */
    public function addNotification(Notification $entity): self
    {
        if (false === $this->notifications->contains($entity)) {
            $this->notifications->add($entity);
        }

        return $this;
    }

    /**
     * Check if user is a defaulter.
     *
     * @return bool
     */
    public function isDefaulter(): bool
    {
        if (false === ($this->getBilling() instanceof Billing)) {
            return false;
        }

        return $this->getBilling()->getPayableInvoices() >= Billing::PAYABLE_INVOICE_LIMIT;
    }

    /**
     * @throws \Exception
     *
     * @return bool
     */
    public function canRestart(): bool
    {
        if (true === (($premium = $this->getPremium()) instanceof Premium)) {
            return $premium->canRestart();
        }

        return false;
    }
}

Comments (1)

  1. Andrew Stark

    A question that constantly comes up from people that care about writing good code, is: what’s the right size for a method or function, or a class, or a package or any other chunk of code? At some point any piece of code can be too big to understand properly – but how big is too big?

    It starts at the method or function level.

    In Code Complete, Steve McConnell says that the theoretical best maximum limit for a method or function is the number of lines that can fit on one screen (i.e., that a developer can see at one time). He then goes on to reference studies from the 1980s and 1990s which found that the sweet spot for functions is somewhere between 65 lines and 200 lines: routines this size are cheaper to develop and have fewer errors per line of code. However, at some point beyond 200 lines you cross into a danger zone where code quality and understandability will fall apart: code that can’t be tested and can’t be changed safely. Eventually you end up with what Michael Feathers calls “runaway methods”: routines that are several hundreds or thousands of lines long and that are constantly being changed and that continuously get bigger and scarier.

    Patrick Duboy looks deeper into this analysis on method length, and points to a more modern study from 2002 that shows that code with shorter routines has fewer defects overall, which matches with most people’s intuition and experience.

    Smaller must be better

    Bob Martin takes the idea that “if small is good, then smaller must be better” to an extreme in Clean Code:

    The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that. Functions should not be 100 lines long. Functions should hardly ever be 20 lines long.

    Martin admits that “This is not an assertion that I can justify. I can’t produce any references to research that shows that very small functions are better.” So like many other rules or best practices in the software development community, this is a qualitative judgement made by someone based on their personal experience writing code – more of an aesthetic argument – or even an ethical one – than an empirical one. Style over substance.

    The same “small is better” guidance applies to classes, packages and subsystems – all of the building blocks of a system. In Code Complete, a study from 1996 found that classes with more routines had more defects. Like functions, according to Clean Code, classes should also be “smaller than small”. Some people recommend that 200 lines is a good limit for a class – not a method, or as few as 50-60 lines (in Ben Nadel’s Object Calisthenics exercise)and that a class should consist of “less than 10” or “not more than 20” methods. The famous C3 project – where Extreme Programming was born – had 12 methods per class on average. And there should be no more than 10 classes per package.

    PMD, a static analysis tool that helps to highlight problems in code structure and style, defines some default values for code size limits: 100 lines per method, 1000 lines per class, and 10 methods in a class. Checkstyle, a similar tool, suggests different limits: 50 lines in a method, 1500 lines in a class.

    Rule of 30

    Looking for guidelines like this led me to the “Rule of 30” in Refactoring in Large Software Projects by Martin Lippert and Stephen Roock:

    If an element consists of more than 30 subelements, it is highly probable that there is a serious problem:

    a) Methods should not have more than an average of 30 code lines (not counting line spaces and comments).

    b) A class should contain an average of less than 30 methods, resulting in up to 900 lines of code.

    c) A package shouldn’t contain more than 30 classes, thus comprising up to 27,000 code lines.

    d) Subsystems with more than 30 packages should be avoided. Such a subsystem would count up to 900 classes with up to 810,000 lines of code.

    e) A system with 30 subsystems would thus possess 27,000 classes and 24.3 million code lines.

    What does this look like? Take a biggish system of 1 million NCLOC. This should break down into:

    • 30,000+ methods
    • 1,000+ classes
    • 30+ packages
    • Hopefully more than 1 subsystem

    How many systems in the real world look like this, or close to this – especially big systems that have been around for a few years?

    Are these rules useful? How should you use them?

    Using code size as the basis for rules like this is simple: easy to see and understand. Too simple, many people would argue: a better indicator of when code is too big is cyclomatic complexity or some other measure of code quality. But some recent studies show that code size actually is a strong predictor of complexity and quality – that

    “complexity metrics are highly correlated with lines of code, and therefore the more complex metrics provide no further information that could not be measured simplify with lines of code”.

    In "Beyond Lines of Code: Do we Need more Complexity Metrics" in Making Software, the authors go so far as to say that lines of code should be considered always as the "first and only metric" for defect prediction, development and maintenance models.

    Recognizing that simple sizing rules are arbitrary, should you use them, and if so how?

    I like the idea of rough and easy-to-understand rules of thumb that you can keep in the back of your mind when writing code or looking at code and deciding whether it should be refactored. The real value of a guideline like the Rule of 30 is when you're reviewing code and identifying risks and costs.

    But enforcing these rules in a heavy handed way on every piece of code as it is being written is foolish. You don’t want to stop when you’re about to write the 31st line in a method – it would slow down work to a crawl. And forcing everyone to break code up to fit arbitrary size limits will make the code worse, not better – the structure will be dominated by short-term decisions.

    As Jeff Langer points out in his chapter discussing Ken Beck’s four rules of Simple Design in Clean Code:

    “Our goal is to keep our overall system small while we are also keeping our functions and classes small. Remember however that this rule is the lowest priority of the four rules of Simple Design. So, although it’s important to keep class and function count low, it’s more important to have tests, eliminate duplication, and express yourself.”

    Sometimes it will take more than 30 lines (or 20 or 5 or whatever the cut-off is) to get a coherent piece of work done. It’s more important to be careful in coming up with the right abstractions and algorithms and to write clean clear code – if a cut-off guideline on size helps to do that, use it. If it doesn't, then don’t bother.

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.