@anonymous/

AttractiveWoodenButtons

PHP (Legacy)

No description

fork
loading
main.php
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
<?php

mb_internal_encoding("utf-8");

abstract class Employee 
{
    private const BOSS_RATE = 0.5;  // надбавка за шефство
    private const RANG_ONE_RATE = 0;    // надбавка за 1 ранг
    private const RANG_TWO_RATE = 0.25; // надбавка за 2 ранг
    private const RANG_THREE_RATE = 0.5;    // надбавка за 3 ранг	

	protected $baseSalary;
    protected $coffeeVolume;
    protected $reportPages;
    protected $rank;
	
    protected $rankPercentage;  // надбавка за ранг работника в процентах 
    protected $isBoss;  // сотрудник является боссом 

    public function __construct(int $baseSalary,
                                int $coffeeVolume,
                                int $reportPages,
                                int $rank,
                                bool $isBoss)
    {
        $this->baseSalary = $baseSalary;
        $this->coffeeVolume = $coffeeVolume;
        $this->reportPages = $reportPages;
        $this->rank = $rank;
        $this->setRankPercentage($rank);
        $this->isBoss = $isBoss;
    }

    /*
	* Внутренний метод, задающий надбавку за ранг сотрудника 	
    */
    protected function setRankPercentage(int $rank) 
    {
        // если ранг не равен 1, 2 или 3 выбрасывается исключение
        if($rank !== 1 && $rank !== 2 && $rank !== 3) {
            throw new Exception("Rank of employee must be equal to 1, 2 or 3.\n Got rank of $rank");
        }
        
        if($rank == 1) {
          $this->rankPercentage = self::RANG_ONE_RATE;
        } elseif ($rank == 2) {
          $this->rankPercentage = self::RANG_TWO_RATE;
        } else {
          $this->rankPercentage = self::RANG_THREE_RATE;
        }
    }

	public function getSalary()
	{
		// возвращает зарплату с надбавкой за ранг и шефство
		$salary = $this->baseSalary + $this->baseSalary * $this->rankPercentage;
		
		return $this->isBoss ? $salary += $salary * self::BOSS_RATE : $salary;           
	}

	public function getCoffeeVolume()
	{
        // босс пьет в два раза больше кофе
		return $this->isBoss ? $this->coffeeVolume * 2 : $this->coffeeVolume;
	}

	public function getReportPages()
	{
        // босс не пишет отчет
		return $this->isBoss ? 0 : $this->reportPages;
	}

	public function getRank()
	{
		if ($this->rankPercentage == 0) {
			return 1;
		} elseif ($this->rankPercentage == 0.25) {
			return 2;
		} else {
			return 3;
		}
	}

	public function isBoss()
	{
		return $this->isBoss;
	}

	public function setBaseSalary(int $salary)
	{
		$this->baseSalary = $salary;
	}

	public function setCoffeeVolume(int $volume)
	{
		$this->coffeeVolume = $volume;
	}

	public function unsetBoss()
	{
		$this->isBoss = false;
	}

	public function setBoss()
	{
		$this->isBoss = true;
	}

	public function setRank(int $rank)
	{
		$this->rank = $rank;
		$this->setRankPercentage($rank);
	}
} 

class Manager extends Employee
{
	private const BASE_SALARY = 500;
	private const COFFEE_VOLUME = 20;
	private const REPORT_PAGES = 200;

	public function __construct(int $rank, bool $isBoss)
	{
		parent::__construct(self::BASE_SALARY,
		                    self::COFFEE_VOLUME,
		                    self::REPORT_PAGES,
		                    $rank,
		                    $isBoss);
	}
}

class Marketer extends Employee
{
	private const BASE_SALARY = 400;
	private const COFFEE_VOLUME = 15;
	private const REPORT_PAGES = 150;

	public function __construct(int $rank, bool $isBoss)
	{
		parent::__construct(self::BASE_SALARY,
		                    self::COFFEE_VOLUME,
		                    self::REPORT_PAGES,
		                    $rank,
		                    $isBoss);
	}
}

class Engineer extends Employee
{
	private const BASE_SALARY = 200;
	private const COFFEE_VOLUME = 5;
	private const REPORT_PAGES = 50;

	public function __construct(int $rank, bool $isBoss)
	{
		parent::__construct(self::BASE_SALARY,
		                    self::COFFEE_VOLUME,
		                    self::REPORT_PAGES,
		                    $rank,
		                    $isBoss);
	}
}

class Analyst extends Employee
{
	private const BASE_SALARY = 800;
	private const COFFEE_VOLUME = 50;
	private const REPORT_PAGES = 5;

	public function __construct(int $rank, bool $isBoss)
	{
		parent::__construct(self::BASE_SALARY,
		                    self::COFFEE_VOLUME,
		                    self::REPORT_PAGES,
		                    $rank,
		                    $isBoss);
	}

}

class Department
{
	private $name;
	private $managers = [];
	private $marketers = [];
	private $engineers = [];
	private $analysts = [];

	public function __construct(string $name)
	{
		$this->name = $name;
	}

	public function getName()
	{
		return $this->name;
	}

	public function addManager(Manager $employee)
	{
		$this->managers[] = $employee;

	}

	public function addMarketer(Marketer $employee)
	{
		$this->marketers[] = $employee;
	}

	public function addEngineer(Engineer $employee)
	{
		$this->engineers[] = $employee;
	}

	public function addAnalyst(Analyst $employee)
	{
		$this->analysts[] = $employee;
	}

	public function getNumberOfEmployees()
	{
		return count($this->managers) + 
		       count($this->marketers) + 
		       count($this->engineers) + 
		       count($this->analysts);
	}

	/* 
	* Выбирает массив значения, заданного в аргументе из массива сотрудников 
	*/
	private static function chooseValues(string $value, array $employees)
	{
		$valueList = [];

		if ($value === "salary") {
			$valueList = array_map(function($emp) { return $emp->getSalary(); }, $employees);
		} elseif ($value === "coffeeVolume") {
			$valueList = array_map(function($emp) { return $emp->getCoffeeVolume(); }, $employees);
		} elseif ($value === "reportPages") {
			$valueList = array_map(function($emp) { return $emp->getReportPages(); }, $employees);
		} else {
			throw new Exception("Requested value /{$value}/ is not defined.\n");
		}

		return $valueList;
	}
    
    /*
	* Возвращает суммарное значение аргумента по всему департаменту
    */
	public function getTotalValue(string $value)
	{
		$managersValue = array_reduce(self::chooseValues($value, $this->managers), 
			                          function($prev,$next) { return $prev += $next; }, 0);
		$marketersValue = array_reduce(self::chooseValues($value, $this->marketers), 
			                           function($prev,$next) { return $prev += $next; }, 0);
		$engineersValue = array_reduce(self::chooseValues($value, $this->engineers), 
			                           function($prev,$next) { return $prev += $next; }, 0);
		$analystsValue = array_reduce(self::chooseValues($value, $this->analysts), 
			                          function($prev,$next) { return $prev += $next; }, 0);

		return $managersValue + $marketersValue + $engineersValue + $analystsValue;
	} 

	private function fireEngineersByRank(int $rank, int $limit)
	{
		$numberOfFired = 0;
		foreach ($this->engineers as $e) {
			if($numberOfFired == $limit) break;  // лимит на увольнение сотрудников
			// если ранг равен указанному в аргументе и сотрудник не босс, увольняем его
           	if($e->getRank() == $rank && !($e->isBoss())) {
				$index = array_search($e, $this->engineers);
				unset($this->engineers[$index]);
				$numberOfFired++;
			}
		}
		return $numberOfFired;
	}

	public function fireEngineers(int $percent)
	{
        // число сотрудников к увольнению с округлением
		$limit = ceil(count($this->engineers) * ($percent / 100)); 
		$firedNumber = $this->fireEngineersByRank(1, $limit);  // сначала уволим 1-го ранга
		
		// если уволенных 1-го ранга меньше необходимого, уволим сотрудников 2-го ранга
		if($firedNumber < $limit) {
			$firedNumber += $this->fireEngineersByRank(2);
		}

		// если уволенных 1-го и 2-го ранга меньше необходимого, уволим сотрудников 3-го ранга
		if($firedNumber < $limit) {
			$firedNumber += $this->fireEngineersByRank(3);
		}
	}

	public function getAnalysts()
	{
		return $this->analysts;
	}

	public function getBoss()
	{
		$allEmployees = array_merge($this->managers,
		                            $this->marketers,
		                            $this->engineers,
		                            $this->analysts);
		foreach($allEmployees as $emp) {
			if($emp->isBoss()) return $emp;
		}		
	}

	private function getFirstRankManagers()
	{
		return array_filter($this->managers, 
		                    function($manager) { return $manager->getRank() === 1; });
	}
	
	private function getSecondRankManagers()
	{
		return array_filter($this->managers, 
		                    function($manager) { return $manager->getRank() === 2; });
	}

	/*
	* Увеличивает ранг менеджера на 1
	*/
	private function upgradeManagersByRank(int $limit, int $rank)
	{
		$counter = 0;
		foreach ($this->managers as $manager) {
			if($counter === $limit) break;
			if($manager->getRank() === $rank) {
				$manager->setRank($rank + 1);
				$counter++;
			}
		}
	}

	public function upgradeManagers(int $percent)
	{
		$rankOneManagers = $this->getFirstRankManagers();
		$rankTwoManagers = $this->getSecondRankManagers();

		// число менеджеров 1-го ранга к повышению с округлением в большую сторону
		$rankOneLimit = (int)ceil(count($rankOneManagers) * ($percent / 100));  

		// число менеджеров 2-го ранга к повышению с округлением в большую сторону
		$rankTwoLimit = (int)ceil(count($rankOneManagers) * ($percent / 100));

		$this->upgradeManagersByRank($rankOneLimit, 1);
		$this->upgradeManagersByRank($rankTwoLimit, 2);
    }
}

class Company
{
    private function createEmployeeGroup(Employee $type, int $numberOfEmployees)
    {
    	$employees = [];
    	for($i = 0; $i < $numberOfEmployees; $i++) {
    		$employees[] = clone $type;
    	}
		return $employees;
    }

    public function addManagersToDepartment(Department $department, 
                                            int $rank,
                                            int $numberOfEmployees)
    {
    	$manager = new Manager($rank, false);
    	$employeeGroup = $this->createEmployeeGroup($manager, $numberOfEmployees);
    	array_walk($employeeGroup, array($department, "addManager"));
    }

    public function addMarketersToDepartment(Department $department, 
                                             int $rank,
                                             int $numberOfEmployees)
    {
    	$marketer = new Marketer($rank, false);
    	$employeeGroup = $this->createEmployeeGroup($marketer, $numberOfEmployees);
    	array_walk($employeeGroup, array($department, "addMarketer"));
    }

    public function addEngineersToDepartment(Department $department, 
                                             int $rank,
                                             int $numberOfEmployees)
    {
    	$engineer = new Engineer($rank, false);
    	$employeeGroup = $this->createEmployeeGroup($engineer, $numberOfEmployees);
    	array_walk($employeeGroup, array($department, "addEngineer"));
    }

    public function addAnalystsToDepartment(Department $department, 
                                           int $rank,
                                           int $numberOfEmployees)
    {
    	$analyst = new Analyst($rank, false);
    	$employeeGroup = $this->createEmployeeGroup($analyst, $numberOfEmployees);
    	array_walk($employeeGroup, array($department, "addAnalyst"));
    }

    private static function getAvg($value, $count)
    {
    	return $value / $count;
    }

    public static function printGeneralReport(array $departments)
    {
    	$header = ["Департамент", "сотр.", "тугр.", "кофе", "стр.", "тугр./стр."];
    	echo self::writeRow($header);
    	echo str_repeat("-", 75) . "\n";
    	
    	foreach($departments as $dep) {
    		self::printDepartmentInfo($dep);
    	}

    	$avgInfo = array_merge(["Среднее"], self::getAvgInfo($departments));
    	$totalInfo = array_merge(["Всего"], self::getTotalInfo($departments));
    	echo self::writeRow($avgInfo);
    	echo self::writeRow($totalInfo);

   	}

   	private static function getAvgInfo(array $departments)
   	{
   		$totalInfo = self::getTotalInfo($departments);
   		$avgInfo = [];
   		foreach ($totalInfo as $piece) {
   			$avgInfo[] = round( ($piece / count($departments)), 2);
   		}
   		return $avgInfo;
   	}

   	private static function getTotalInfo(array $departments)
   	{
   		$empsInTotal = 0;
		$totalSalary = 0;
		$totalCoffeeVolume = 0;
		$totalReportPages = 0;
		$totalRatio = 0;

		foreach ($departments as $dep) {
			$empsInTotal += $dep->getNumberOfEmployees();
			$totalSalary += $dep->getTotalValue("salary");
			$totalCoffeeVolume += $dep->getTotalValue("coffeeVolume");
			$totalReportPages += $dep->getTotalValue("reportPages");
			$totalRatio += round( ($totalSalary / $totalReportPages), 2);
		}

		return [$empsInTotal, $totalSalary, $totalCoffeeVolume, $totalReportPages, $totalRatio];
   	}

    private static function printDepartmentInfo(Department $dep)
    {
    	$info = [];
    	$depName = $dep->getName();
    	$allEmployees = $dep->getNumberOfEmployees();
    	$salary = $dep->getTotalValue("salary");
	    $coffeeVolume = $dep->getTotalValue("coffeeVolume");
	    $reportPages = $dep->getTotalValue("reportPages");
	    $ratio = round(($salary / $reportPages), 2);
	    array_push($info, $depName, $allEmployees, $salary, $coffeeVolume, $reportPages, $ratio);   		
    	echo self::writeRow($info);
    }

    private static function writeRow(array $info)
	{
		$result = "";
		foreach ($info as $piece) {
			$result .= $piece . str_repeat(" ", 12 - mb_strlen($piece));
		}
		return $result . "\n";
	}
}

/*
* Создание компании и устройство сотрудников,
* вывод отчета, применение антикризисных мер
*/
function organizeCompany()
{
	// ТОО "Вектор"
	$vector = new Company();
	
	// Все департаменты
	$allDepartments = [];

	$purchasesDepartment = new Department("Закупок");
	$salesDepartment = new Department("Продаж");
	$marketingDepartment = new Department("Рекламы");
	$logisticsDepartment = new Department("Логистики");

    // Заполнение департамента закупок сотрудниками
    $vector->addManagersToDepartment($purchasesDepartment, 1, 9); 	// 9×ме1
    $vector->addManagersToDepartment($purchasesDepartment, 2, 3);  	// 3×ме2
    $vector->addManagersToDepartment($purchasesDepartment, 3, 2); 	// 2×ме3 
    $vector->addMarketersToDepartment($purchasesDepartment, 1, 2); 	// 2×ма1
    $purchasesDepartmentBoss = new Manager(2, true);
    $purchasesDepartment->addManager($purchasesDepartmentBoss);
    $allDepartments[] = $purchasesDepartment;

    // Заполнение департамента продаж сотрудниками
    $vector->addManagersToDepartment($salesDepartment, 1, 12); 
    $vector->addMarketersToDepartment($salesDepartment, 1, 6);
    $vector->addAnalystsToDepartment($salesDepartment, 1, 3);
    $vector->addAnalystsToDepartment($salesDepartment, 2, 2);
    $salesDepartmentBoss = new Marketer(2, true);
    $salesDepartment->addMarketer($salesDepartmentBoss);
    $allDepartments[] = $salesDepartment;

    // Заполнение департамента рекламы сотрудниками
    $vector->addMarketersToDepartment($marketingDepartment, 1, 15);
    $vector->addMarketersToDepartment($marketingDepartment, 2, 10);
    $vector->addManagersToDepartment($marketingDepartment, 1, 8);
    $vector->addEngineersToDepartment($marketingDepartment, 1, 2);
    $marketingDepartmentBoss = new Marketer(3, true);
    $marketingDepartment->addMarketer($marketingDepartmentBoss);
    $allDepartments[] = $marketingDepartment;

    // Заполнение департамента логистики сотрудниками
    $vector->addManagersToDepartment($logisticsDepartment, 1, 13);
    $vector->addManagersToDepartment($logisticsDepartment, 2, 5);
    $vector->addEngineersToDepartment($logisticsDepartment, 1, 5);
    $logisticsDepartmentBoss = new Manager(1, true);
    $logisticsDepartment->addManager($logisticsDepartmentBoss);
    $allDepartments[] = $logisticsDepartment;    

    // клонируем департаменты для тестирования антикризисных мер 
    $clonedDepartments = [];
    for($i = 0; $i < 3; $i++) {
    	$cloned = [];
    	$cloned[] = clone $purchasesDepartment;
    	$cloned[] = clone $salesDepartment;
    	$cloned[] = clone $marketingDepartment;
    	$cloned[] = clone $logisticsDepartment;
    	$clonedDepartments[] = $cloned; 
    }

    // Вывод в виде таблицы информации о компании
    echo "До кризиса.\n";
    $vector->printGeneralReport($allDepartments);
    echo "\n\n";

    // Применение антикризисных мер и вывод результата
    tryAnticrisisScenario1($clonedDepartments[0]);
    $vector->printGeneralReport($clonedDepartments[0]);
    echo "\n\n";
    tryAnticrisisScenario2($clonedDepartments[1]);
    $vector->printGeneralReport($clonedDepartments[1]);
    echo "\n\n";
    tryAnticrisisScenario3($clonedDepartments[2]);
    $vector->printGeneralReport($clonedDepartments[2]);
}

organizeCompany();

/*
* Антикризисный сценарий №1 по сокращению инженеров
*/
function tryAnticrisisScenario1(array $departments)
{
	echo "Сценарий 1. Сокращение инженеров\n";
	foreach ($departments as $dep) {
		$dep->fireEngineers(40);
	}
}

/*
* Антикризисный сценарий №2 по стимулированию аналитиков
*/
function tryAnticrisisScenario2(array $departments)
{
	function cmp_analysts($analyst1, $analyst2)
	{
		if($analyst1.getRank() == $analyst2.getRank()) return 0;
		return ($analyst1.getRank() > $analyst2.getRank()) ? +1 : -0;
	}

	echo "Сценарий 2. Прокачка аналитиков\n";
	foreach ($departments as $dep) {
		if(!$dep->getAnalysts()) continue;
		$topRank = 0;
		$topAnalyst = null;
		foreach($dep->getAnalysts() as $analyst) {
			if($analyst->getRank() > $topRank) {
				$topRank = $analyst->getRank();
				$topAnalyst = $analyst;
			}
			$analyst->setBaseSalary(1100);
			$analyst->setCoffeeVolume(75);
		}
		$currentBoss = $dep->getBoss();
		if( !($currentBoss instanceof Analyst) ) {
			$currentBoss->unsetBoss();
			$topAnalyst->setBoss();
		} 
	}
}

/*
* Антикризисный сценарий №3 по стимулированию менеджеров
*/

function tryAnticrisisScenario3(array $departments)
{
	echo "Сценарий 3. Прокачка менеджеров\n";
	foreach ($departments as $dep) {
		$dep->upgradeManagers(50);
	}
}

PHP 7.0.8 (Legacy: use the following for new features: Command-line PHP: https://repl.it/languages/php_cli PHP Web Server: https://repl.it/languages/php7