From f7d4b48b25f08d6cfd016fb47989d9b1088aa84d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Fontaine?= Date: Sat, 20 Jan 2018 15:23:36 +0100 Subject: [PATCH] follow the PSR2 coding style rules --- .../Controller/DefaultController.php | 36 +- src/InsaLan/ApiBundle/Http/JsonResponse.php | 6 +- src/InsaLan/InsaLanBundle/API/Lol.php | 24 +- .../Resources/public/css/global.css | 6 +- .../Resources/public/js/global.js | 84 +-- .../Resources/public/js/tournament.js | 519 +++++++++--------- .../InsaLanBundle/Service/FreeSlots.php | 24 +- .../Subscriber/TablePrefixSubscriber.php | 2 +- .../DataFixtures/ORM/NewsLoader.php | 1 - src/InsaLan/NewsBundle/Entity/News.php | 8 +- .../NewsBundle/Entity/NewsRepository.php | 4 +- src/InsaLan/NewsBundle/Entity/Slider.php | 3 +- .../NewsBundle/Entity/SliderRepository.php | 4 +- .../Controller/AdminController.php | 51 +- .../Controller/DefaultController.php | 18 +- .../DataFixtures/ORM/OrderLoader.php | 7 +- .../DataFixtures/ORM/PizzaLoader.php | 5 +- .../DataFixtures/ORM/UserOrderLoader.php | 7 +- src/InsaLan/PizzaBundle/Entity/Order.php | 36 +- .../PizzaBundle/Entity/OrderRepository.php | 14 +- src/InsaLan/PizzaBundle/Entity/Pizza.php | 11 +- src/InsaLan/PizzaBundle/Entity/UserOrder.php | 24 +- .../Entity/UserOrderRepository.php | 4 +- .../TournamentBundle/Admin/GroupAdmin.php | 24 +- .../TournamentBundle/Admin/ManagerAdmin.php | 1 - .../TournamentBundle/Admin/MatchAdmin.php | 19 +- .../TournamentBundle/Admin/PlayerAdmin.php | 1 - .../TournamentBundle/Admin/RoundAdmin.php | 21 +- .../TournamentBundle/Admin/TeamAdmin.php | 4 +- .../Admin/TournamentAdmin.php | 22 +- .../Controller/AdminController.php | 91 +-- .../Controller/CRUDController.php | 2 - .../Controller/DefaultController.php | 46 +- .../Controller/ManagerController.php | 103 ++-- .../Controller/MerchantController.php | 41 +- .../Controller/UserController.php | 339 +++++++----- .../DataFixtures/ORM/RoundLoader.php | 3 +- .../DataFixtures/ORM/TeamLoader.php | 2 +- .../DataFixtures/ORM/TournamentLoader.php | 8 +- src/InsaLan/TournamentBundle/Entity/Group.php | 21 +- .../Entity/GroupRepository.php | 4 +- .../TournamentBundle/Entity/GroupStage.php | 9 +- .../TournamentBundle/Entity/Knockout.php | 16 +- .../TournamentBundle/Entity/KnockoutMatch.php | 69 ++- .../Entity/KnockoutMatchRepository.php | 214 ++++---- .../TournamentBundle/Entity/Manager.php | 15 +- .../Entity/ManagerRepository.php | 5 +- src/InsaLan/TournamentBundle/Entity/Match.php | 63 ++- .../TournamentBundle/Entity/Participant.php | 12 +- .../Entity/ParticipantRepository.php | 14 +- .../TournamentBundle/Entity/Player.php | 54 +- .../Entity/PlayerRepository.php | 30 +- src/InsaLan/TournamentBundle/Entity/Round.php | 16 +- src/InsaLan/TournamentBundle/Entity/Team.php | 28 +- .../Entity/TeamRepository.php | 19 +- .../TournamentBundle/Entity/Tournament.php | 50 +- .../Entity/TournamentRepository.php | 22 +- .../TournamentBundle/Service/Placement.php | 7 +- .../TournamentBundle/Service/PvpNet.php | 34 +- .../Subscriber/ParticipantValidator.php | 108 ++-- .../Validator/Constraint/ExistingLolId.php | 10 +- .../UserBundle/Admin/DiscountAdmin.php | 1 - .../UserBundle/Admin/MerchantOrderAdmin.php | 1 - src/InsaLan/UserBundle/Admin/UserAdmin.php | 1 - .../Controller/DefaultController.php | 21 +- src/InsaLan/UserBundle/Entity/Discount.php | 4 +- .../UserBundle/Entity/MerchantOrder.php | 2 +- .../UserBundle/Entity/PaymentDetails.php | 9 +- src/InsaLan/UserBundle/Entity/User.php | 23 +- .../Exception/ControllerException.php | 2 +- src/InsaLan/UserBundle/Service/Payment.php | 24 +- 71 files changed, 1370 insertions(+), 1163 deletions(-) diff --git a/src/InsaLan/ApiBundle/Controller/DefaultController.php b/src/InsaLan/ApiBundle/Controller/DefaultController.php index 374c1074..b6f33112 100644 --- a/src/InsaLan/ApiBundle/Controller/DefaultController.php +++ b/src/InsaLan/ApiBundle/Controller/DefaultController.php @@ -32,9 +32,9 @@ public function indexAction(Request $request) // look for a manager corresponding to user and provieded tournaments $manager = $em->getRepository('InsaLanTournamentBundle:Manager')->findByUser($usr); foreach ($manager as $m) { - if ($m->getTournament()) - if (in_array($m->getTournament()->getShortname(),$t)) - if($m->getPaymentDone()) { + if ($m->getTournament()) { + if (in_array($m->getTournament()->getShortname(), $t)) { + if ($m->getPaymentDone()) { $res["err"] = null; $res["tournament"] = "manager"; @@ -43,28 +43,30 @@ public function indexAction(Request $request) $res["err"] = "no_paid_place"; // no return because we need to check if there is a player timezone_offset_get() } + } + } } $player = $em->getRepository('InsaLanTournamentBundle:Player')->findByUser($usr); - foreach($player as $p) { + foreach ($player as $p) { $res["err"] = "no_paid_place"; if ($p->getTournament()) { - if (in_array($p->getTournament()->getShortname(),$t)) - if($p->getPaymentDone()) { - $res["err"] = null; - $res["tournament"] = $p->getTournament()->getShortname(); - return new JsonResponse($res); + if (in_array($p->getTournament()->getShortname(), $t)) { + if ($p->getPaymentDone()) { + $res["err"] = null; + $res["tournament"] = $p->getTournament()->getShortname(); + return new JsonResponse($res); + } } - } - - elseif ($p->getPendingTournament()) { - if (in_array($p->getPendingTournament()->getShortname(),$t)) - if($p->getPaymentDone()) { - $res["err"] = null; - $res["tournament"] = $p->getPendingTournament()->getShortname(); - return new JsonResponse($res); + } elseif ($p->getPendingTournament()) { + if (in_array($p->getPendingTournament()->getShortname(), $t)) { + if ($p->getPaymentDone()) { + $res["err"] = null; + $res["tournament"] = $p->getPendingTournament()->getShortname(); + return new JsonResponse($res); + } } } } diff --git a/src/InsaLan/ApiBundle/Http/JsonResponse.php b/src/InsaLan/ApiBundle/Http/JsonResponse.php index 47b6b1d5..ed8c2779 100644 --- a/src/InsaLan/ApiBundle/Http/JsonResponse.php +++ b/src/InsaLan/ApiBundle/Http/JsonResponse.php @@ -4,8 +4,10 @@ use Symfony\Component\HttpFoundation\Response; -class JsonResponse extends Response { - public function __construct($data) { +class JsonResponse extends Response +{ + public function __construct($data) + { parent::__construct(); $this->headers->set('Content-Type', 'application/json'); $this->setContent(json_encode($data)); diff --git a/src/InsaLan/InsaLanBundle/API/Lol.php b/src/InsaLan/InsaLanBundle/API/Lol.php index ae5416da..90025142 100644 --- a/src/InsaLan/InsaLanBundle/API/Lol.php +++ b/src/InsaLan/InsaLanBundle/API/Lol.php @@ -5,17 +5,19 @@ class Lol { - protected $api; + protected $api; - public function __construct($apiKey) { - $this->api = new Api($apiKey); - $this->api->setRegion('euw'); - //$this->api->remember(20); - //$this->api->limit(10, 10); // Set a limit of 10 requests per 10 seconds - //$this->api->limit(500, 600); // Set a limit of 500 requests per 600 (10 minutes) seconds - } + public function __construct($apiKey) + { + $this->api = new Api($apiKey); + $this->api->setRegion('euw'); + //$this->api->remember(20); + //$this->api->limit(10, 10); // Set a limit of 10 requests per 10 seconds + //$this->api->limit(500, 600); // Set a limit of 500 requests per 600 (10 minutes) seconds + } - public function getApi() { - return $this->api; - } + public function getApi() + { + return $this->api; + } } diff --git a/src/InsaLan/InsaLanBundle/Resources/public/css/global.css b/src/InsaLan/InsaLanBundle/Resources/public/css/global.css index 2e007ebd..5888f372 100644 --- a/src/InsaLan/InsaLanBundle/Resources/public/css/global.css +++ b/src/InsaLan/InsaLanBundle/Resources/public/css/global.css @@ -913,7 +913,7 @@ li a:hover { } .text-justify { - text-align: justify; + text-align: justify; } .text-center { @@ -954,8 +954,8 @@ li a:hover { /** FOR STREAMS ONLY, TEMPORARY */ .streamsHeader { - top: 0px; - width: 100%; + top: 0px; + width: 100%; height: 40px; font-family: Oswald, sans-serif; font-size: 20px; diff --git a/src/InsaLan/InsaLanBundle/Resources/public/js/global.js b/src/InsaLan/InsaLanBundle/Resources/public/js/global.js index 03c7cfc1..e2abece5 100644 --- a/src/InsaLan/InsaLanBundle/Resources/public/js/global.js +++ b/src/InsaLan/InsaLanBundle/Resources/public/js/global.js @@ -1,53 +1,53 @@ -window.addEvent('domready', function() { +window.addEvent('domready', function () { // Close button for alert messages - $$('.alert-error, .alert-info, .alert-success').each(function(e) { - var button = new Element('button', { - type: 'button', - html: '×', - events: { - click: function() { - var fx = new Fx.Tween(this.parentNode, { - property: 'opacity', - onComplete: function() { - this.parentNode.dispose(); - }.bind(this) - }); + $$('.alert-error, .alert-info, .alert-success').each(function (e) { + var button = new Element('button', { + type: 'button', + html: '×', + events: { + click: function () { + var fx = new Fx.Tween(this.parentNode, { + property: 'opacity', + onComplete: function () { + this.parentNode.dispose(); + }.bind(this) + }); - fx.start(1, 0); - } - } - }); + fx.start(1, 0); + } + } + }); - button.inject(e, 'top'); - }); + button.inject(e, 'top'); + }); - { // Highlight current module - var module = window.location.pathname; - if (module == '/' || module == '/app_dev.php/') { - module += 'news/'; - } + { // Highlight current module + var module = window.location.pathname; + if (module == '/' || module == '/app_dev.php/') { + module += 'news/'; + } - $$('body > header nav li a').each(function(a) { - var p = a.pathname; - if (p == '/' || p == '/app_dev.php/') { - p += 'news/'; - } + $$('body > header nav li a').each(function (a) { + var p = a.pathname; + if (p == '/' || p == '/app_dev.php/') { + p += 'news/'; + } - if (0 === module.lastIndexOf(p, 0)) { - a.parentNode.addClass('active'); - } - }); - } + if (0 === module.lastIndexOf(p, 0)) { + a.parentNode.addClass('active'); + } + }); + } // Streams actions - $$(".hideMask").addEvent("click", function() { - $$(".maskContent").hide(); - $$("#mask").hide(); - }); + $$(".hideMask").addEvent("click", function () { + $$(".maskContent").hide(); + $$("#mask").hide(); + }); - $$(".showMask").addEvent("click", function() { - $$("#" + this.dataset.target).show(); - $$("#mask").show(); - }); + $$(".showMask").addEvent("click", function () { + $$("#" + this.dataset.target).show(); + $$("#mask").show(); + }); }); diff --git a/src/InsaLan/InsaLanBundle/Resources/public/js/tournament.js b/src/InsaLan/InsaLanBundle/Resources/public/js/tournament.js index f62d63c6..f694b508 100644 --- a/src/InsaLan/InsaLanBundle/Resources/public/js/tournament.js +++ b/src/InsaLan/InsaLanBundle/Resources/public/js/tournament.js @@ -1,255 +1,264 @@ -function parseGame(data) -{ - var rounds = []; - - for (var k = 0; k < data.rounds.length; ++k) { - // Figure out who is the winner - var winner = (data.rounds[k].score[0] > data.rounds[k].score[1]) ? 0 : 1; - var wName = data.match.participants[winner].name; - var lName = data.match.participants[1 - winner].name; - - var round = {}; - var blob = data.rounds[k].blob; - - for (var i in blob.participants) { - if (!blob.participants.hasOwnProperty(i)) continue; - - var p = {}; - p.id = blob.participantIdentities[i].player.summonerId; - p.name = blob.participantIdentities[i].player.summonerName; - p.items = [ - blob.participants[i].stats.item0, - blob.participants[i].stats.item1, - blob.participants[i].stats.item2, - blob.participants[i].stats.item3, - blob.participants[i].stats.item4, - blob.participants[i].stats.item5, - blob.participants[i].stats.item6 - ]; - p.kills = blob.participants[i].stats.kills; - p.deaths = blob.participants[i].stats.deaths; - p.assists = blob.participants[i].stats.assists; - p.gold = blob.participants[i].stats.goldEarned; - p.level = blob.participants[i].stats.champLevel; - p.cs = blob.participants[i].stats.minionsKilled; - p.lane = blob.participants[i].timeline.lane; - - p.teamId = blob.participants[i].teamId; - p.championId = blob.participants[i].championId - p.spells = [ - blob.participants[i].spell1Id, - blob.participants[i].spell2Id - ]; - - if (!round[p.teamId]) { - round[p.teamId] = {}; - round[p.teamId].isWinner = blob.participants[i].stats.winner; - round[p.teamId].participants = []; - round[p.teamId].name = blob.participants[i].stats.winner ? wName : lName; - } - - round[p.teamId].participants.push(p); - } - - rounds.push(round); - } - - return rounds; -} - -function getChamp(key) -{ - for (var i in _champion.data) { - if (key == _champion.data[i].key) { - return _champion.data[i].image; - } - } - return null; -} - -function getSummoner(key) -{ - for (var i in _summoner.data) { - if (key == _summoner.data[i].key) { - return _summoner.data[i].image; - } - } - return null; -} - -function getItem(key) -{ - if (_item.data[key]) { - return _item.data[key].image; - } - - return null; -} - -function formatImg(img) -{ - var h = 36; - var w = 36; - - if (!img) { - return ''; - } - - var t = ''; - return t; -} - -function drawTeam(team, target) -{ - team.participants.sort(function(a, b) { - var lanes = ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM']; - if (lanes.indexOf(a.lane) != lanes.indexOf(b.lane)) { - return (lanes.indexOf(a.lane) < lanes.indexOf(b.lane)) ? -1 : 1; - } - - return (a.cs > b.cs) ? -1 : 1; - }); - - for (var i = 0; i < team.participants.length; ++i) { - var el = $('champ-template').clone(true); - el.addClass('player'); - el.getElements('.name')[0].set('text', team.participants[i].name); - - el.getElements('.champ')[0].set('html', - formatImg(getChamp(team.participants[i].championId))); - el.getElements('.level')[0].set('text', team.participants[i].level); - el.getElements('.kda')[0].set('text', - team.participants[i].kills + '/' + - team.participants[i].deaths + '/' + - team.participants[i].assists); - - for (var j = 0; j < team.participants[i].items.length; ++j) { - el.getElements('.item' + j)[0].set('html', - formatImg(getItem(team.participants[i].items[j]))); - } - - for (var j = 0; j < team.participants[i].spells.length; ++j) { - el.getElements('.spell' + j)[0].set('html', - formatImg(getSummoner(team.participants[i].spells[j]))); - } - - var gold = (Math.round(team.participants[i].gold / 100) / 10) + 'k'; - el.getElements('.gold')[0].set('text', gold); - el.getElements('.cs')[0].set('text', team.participants[i].cs); - - el.setStyle('display', ''); - el.inject(target); - } - - $(target).getElements('caption')[0].set('text', team.name); - if (team.isWinner) { - var winner = new Element('span'); - winner.className = 'winner'; - winner.set('text', 'Vainqueur'); - winner.inject($(target).getElements('caption')[0], 'top'); - } -} - -function loadMatch(id, target) -{ - if (!loadMatch.spinner) { - loadMatch.spinner = new Spinner(target); - } - - target.setStyle('display', ''); - loadMatch.spinner.show(); - - var req = new Request.JSON({ - url: loadMatch.url.replace(/__id__/g, id), - onSuccess: function(data) { - var team = target.getElements('.team'); - target.getElements('h3').set('text', ''); - - for (var i = 0; i < 2; ++i) { - team[i].getElements('h3')[0].set('text', data.match.participants[i].name); - team[i].getElements('.rank span')[0].set('text', data.match.participants[i].rank); - team[i].getElements('.won')[0].set('text', data.match.participants[i].won + "W"); - team[i].getElements('.lost')[0].set('text', data.match.participants[i].lost + "L"); - } - - var score = [0, 0]; - for (var i = 0; i < data.rounds.length; ++i) { - if (data.rounds[i].score[0] > data.rounds[i].score[1]) { - ++score[0]; - } - else if (data.rounds[i].score[0] < data.rounds[i].score[1]) { - ++score[1]; - } - } - - target.getElements('.score').set('text', score.join("-")); - - var header = target.getElements('header')[0]; - header.removeClass('wleft'); - header.removeClass('wright'); - if (score[0] > score[1]) { - header.addClass('wleft'); - } - else if (score[0] < score[1]) { - header.addClass('wright'); - } - - var rounds = parseGame(data); - var li = target.getElements('.rounds nav ul li'); - li.set('text', '-'); - li.removeClass('active'); - li.addClass('disabled'); - - for (var i = 0; i < data.rounds.length; ++i) { - li[i].set('text', 'Game ' + (i + 1)); - li[i].removeClass('disabled'); - } - - loadMatch.spinner.hide(); - loadMatch.rounds = rounds; - loadMatch.data = data; - loadRound(target, li[0]); - } - }).get(); -} -loadMatch.spinner = null; -loadMatch.rounds = null; -loadMatch.data = null; - - -function loadRound(target, li) -{ - if (!loadMatch.rounds) { - return; - } - - var rid = parseInt(li.dataset.rid); - - target.getElements('tr.player').each(function(t) { t.dispose(); }); - target.getElements('.winner').dispose(); - - drawTeam(loadMatch.rounds[rid][100], 'team100'); - drawTeam(loadMatch.rounds[rid][200], 'team200'); - - var dl = target.getElements('.download')[0]; - if (loadMatch.data.rounds[rid].replay) { - for (var i = 0; i < 5; ++i) { - dl.removeClass('g' + i); - } - - dl.addClass('g' + (rid + 1)); - dl.getElements('a')[0].href = loadRound.replayUrl + loadMatch.data.rounds[rid].replay; - dl.setStyle('visibility', ''); - } - else { - dl.setStyle('visibility', 'hidden'); - } - - li.parentNode.getElements('li').removeClass('active'); - li.addClass('active'); -} +function parseGame(data) +{ + var rounds = []; + + for (var k = 0; k < data.rounds.length; ++k) { + // Figure out who is the winner + var winner = (data.rounds[k].score[0] > data.rounds[k].score[1]) ? 0 : 1; + var wName = data.match.participants[winner].name; + var lName = data.match.participants[1 - winner].name; + + var round = {}; + var blob = data.rounds[k].blob; + + for (var i in blob.participants) { + if (!blob.participants.hasOwnProperty(i)) { + continue; + } + + var p = {}; + p.id = blob.participantIdentities[i].player.summonerId; + p.name = blob.participantIdentities[i].player.summonerName; + p.items = [ + blob.participants[i].stats.item0, + blob.participants[i].stats.item1, + blob.participants[i].stats.item2, + blob.participants[i].stats.item3, + blob.participants[i].stats.item4, + blob.participants[i].stats.item5, + blob.participants[i].stats.item6 + ]; + p.kills = blob.participants[i].stats.kills; + p.deaths = blob.participants[i].stats.deaths; + p.assists = blob.participants[i].stats.assists; + p.gold = blob.participants[i].stats.goldEarned; + p.level = blob.participants[i].stats.champLevel; + p.cs = blob.participants[i].stats.minionsKilled; + p.lane = blob.participants[i].timeline.lane; + + p.teamId = blob.participants[i].teamId; + p.championId = blob.participants[i].championId + p.spells = [ + blob.participants[i].spell1Id, + blob.participants[i].spell2Id + ]; + + if (!round[p.teamId]) { + round[p.teamId] = {}; + round[p.teamId].isWinner = blob.participants[i].stats.winner; + round[p.teamId].participants = []; + round[p.teamId].name = blob.participants[i].stats.winner ? wName : lName; + } + + round[p.teamId].participants.push(p); + } + + rounds.push(round); + } + + return rounds; +} + +function getChamp(key) +{ + for (var i in _champion.data) { + if (key == _champion.data[i].key) { + return _champion.data[i].image; + } + } + return null; +} + +function getSummoner(key) +{ + for (var i in _summoner.data) { + if (key == _summoner.data[i].key) { + return _summoner.data[i].image; + } + } + return null; +} + +function getItem(key) +{ + if (_item.data[key]) { + return _item.data[key].image; + } + + return null; +} + +function formatImg(img) +{ + var h = 36; + var w = 36; + + if (!img) { + return ''; + } + + var t = ''; + return t; +} + +function drawTeam(team, target) +{ + team.participants.sort(function (a, b) { + var lanes = ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM']; + if (lanes.indexOf(a.lane) != lanes.indexOf(b.lane)) { + return (lanes.indexOf(a.lane) < lanes.indexOf(b.lane)) ? -1 : 1; + } + + return (a.cs > b.cs) ? -1 : 1; + }); + + for (var i = 0; i < team.participants.length; ++i) { + var el = $('champ-template').clone(true); + el.addClass('player'); + el.getElements('.name')[0].set('text', team.participants[i].name); + + el.getElements('.champ')[0].set( + 'html', + formatImg(getChamp(team.participants[i].championId)) + ); + el.getElements('.level')[0].set('text', team.participants[i].level); + el.getElements('.kda')[0].set( + 'text', + team.participants[i].kills + '/' + + team.participants[i].deaths + '/' + + team.participants[i].assists + ); + + for (var j = 0; j < team.participants[i].items.length; ++j) { + el.getElements('.item' + j)[0].set( + 'html', + formatImg(getItem(team.participants[i].items[j])) + ); + } + + for (var j = 0; j < team.participants[i].spells.length; ++j) { + el.getElements('.spell' + j)[0].set( + 'html', + formatImg(getSummoner(team.participants[i].spells[j])) + ); + } + + var gold = (Math.round(team.participants[i].gold / 100) / 10) + 'k'; + el.getElements('.gold')[0].set('text', gold); + el.getElements('.cs')[0].set('text', team.participants[i].cs); + + el.setStyle('display', ''); + el.inject(target); + } + + $(target).getElements('caption')[0].set('text', team.name); + if (team.isWinner) { + var winner = new Element('span'); + winner.className = 'winner'; + winner.set('text', 'Vainqueur'); + winner.inject($(target).getElements('caption')[0], 'top'); + } +} + +function loadMatch(id, target) +{ + if (!loadMatch.spinner) { + loadMatch.spinner = new Spinner(target); + } + + target.setStyle('display', ''); + loadMatch.spinner.show(); + + var req = new Request.JSON({ + url: loadMatch.url.replace(/__id__/g, id), + onSuccess: function (data) { + var team = target.getElements('.team'); + target.getElements('h3').set('text', ''); + + for (var i = 0; i < 2; ++i) { + team[i].getElements('h3')[0].set('text', data.match.participants[i].name); + team[i].getElements('.rank span')[0].set('text', data.match.participants[i].rank); + team[i].getElements('.won')[0].set('text', data.match.participants[i].won + "W"); + team[i].getElements('.lost')[0].set('text', data.match.participants[i].lost + "L"); + } + + var score = [0, 0]; + for (var i = 0; i < data.rounds.length; ++i) { + if (data.rounds[i].score[0] > data.rounds[i].score[1]) { + ++score[0]; + } else if (data.rounds[i].score[0] < data.rounds[i].score[1]) { + ++score[1]; + } + } + + target.getElements('.score').set('text', score.join("-")); + + var header = target.getElements('header')[0]; + header.removeClass('wleft'); + header.removeClass('wright'); + if (score[0] > score[1]) { + header.addClass('wleft'); + } else if (score[0] < score[1]) { + header.addClass('wright'); + } + + var rounds = parseGame(data); + var li = target.getElements('.rounds nav ul li'); + li.set('text', '-'); + li.removeClass('active'); + li.addClass('disabled'); + + for (var i = 0; i < data.rounds.length; ++i) { + li[i].set('text', 'Game ' + (i + 1)); + li[i].removeClass('disabled'); + } + + loadMatch.spinner.hide(); + loadMatch.rounds = rounds; + loadMatch.data = data; + loadRound(target, li[0]); + } + }).get(); +} +loadMatch.spinner = null; +loadMatch.rounds = null; +loadMatch.data = null; + + +function loadRound(target, li) +{ + if (!loadMatch.rounds) { + return; + } + + var rid = parseInt(li.dataset.rid); + + target.getElements('tr.player').each(function (t) { + t.dispose(); }); + target.getElements('.winner').dispose(); + + drawTeam(loadMatch.rounds[rid][100], 'team100'); + drawTeam(loadMatch.rounds[rid][200], 'team200'); + + var dl = target.getElements('.download')[0]; + if (loadMatch.data.rounds[rid].replay) { + for (var i = 0; i < 5; ++i) { + dl.removeClass('g' + i); + } + + dl.addClass('g' + (rid + 1)); + dl.getElements('a')[0].href = loadRound.replayUrl + loadMatch.data.rounds[rid].replay; + dl.setStyle('visibility', ''); + } else { + dl.setStyle('visibility', 'hidden'); + } + + li.parentNode.getElements('li').removeClass('active'); + li.addClass('active'); +} + diff --git a/src/InsaLan/InsaLanBundle/Service/FreeSlots.php b/src/InsaLan/InsaLanBundle/Service/FreeSlots.php index 3a7d0d75..447db647 100644 --- a/src/InsaLan/InsaLanBundle/Service/FreeSlots.php +++ b/src/InsaLan/InsaLanBundle/Service/FreeSlots.php @@ -14,7 +14,8 @@ use InsaLan\TournamentBundle\Entity\Participant; class FreeSlots -{ +{ + const TOTAL_SLOTS = 64; protected $doctrine; @@ -28,7 +29,7 @@ public function __construct(Registry $doctrine) * @return int Number of free slots currently available. */ public function get() - { + { return self::TOTAL_SLOTS - count($this->doctrine ->getRepository('InsaLanTournamentBundle:Participant') ->findByValidated(Participant::STATUS_VALIDATED)); @@ -37,14 +38,20 @@ public function get() /** * @return Participant The next participant to send to validated state, or null if not available. */ - public function selectWaitingTeam() { + public function selectWaitingTeam() + { $participant = $this->doctrine ->getRepository('InsaLanTournamentBundle:Participant') - ->findBy(array("validated" => Participant::STATUS_WAITING), //select - array("id" => "ASC"), //order by - 1); //limit - if(count($participant) === 1) return $participant[0]; - else return null; + ->findBy( + array("validated" => Participant::STATUS_WAITING), //select + array("id" => "ASC"), //order by + 1 + ); //limit + if (count($participant) === 1) { + return $participant[0]; + } else { + return null; + } } public function opened() @@ -53,4 +60,3 @@ public function opened() return (time() >= $date); } } -?> \ No newline at end of file diff --git a/src/InsaLan/InsaLanBundle/Subscriber/TablePrefixSubscriber.php b/src/InsaLan/InsaLanBundle/Subscriber/TablePrefixSubscriber.php index 002613fb..d5563338 100644 --- a/src/InsaLan/InsaLanBundle/Subscriber/TablePrefixSubscriber.php +++ b/src/InsaLan/InsaLanBundle/Subscriber/TablePrefixSubscriber.php @@ -1,5 +1,6 @@ flush(); } } - diff --git a/src/InsaLan/NewsBundle/Entity/News.php b/src/InsaLan/NewsBundle/Entity/News.php index fbb2ccb9..82309d2b 100644 --- a/src/InsaLan/NewsBundle/Entity/News.php +++ b/src/InsaLan/NewsBundle/Entity/News.php @@ -38,12 +38,12 @@ class News protected $text; /** - * @ORM\Column(type="datetime") + * @ORM\Column(type="datetime") */ private $createdAt; /** - * @ORM\Column(type="datetime") + * @ORM\Column(type="datetime") */ private $updatedAt; @@ -152,7 +152,7 @@ public function setCreatedAt($createdAt) /** * Get createdAt * - * @return \DateTime + * @return \DateTime */ public function getCreatedAt() { @@ -175,7 +175,7 @@ public function setUpdatedAt($updatedAt) /** * Get updatedAt * - * @return \DateTime + * @return \DateTime */ public function getUpdatedAt() { diff --git a/src/InsaLan/NewsBundle/Entity/NewsRepository.php b/src/InsaLan/NewsBundle/Entity/NewsRepository.php index 10d3c30c..abe1b0f6 100644 --- a/src/InsaLan/NewsBundle/Entity/NewsRepository.php +++ b/src/InsaLan/NewsBundle/Entity/NewsRepository.php @@ -14,7 +14,9 @@ class NewsRepository extends EntityRepository { public function getLatest($nb) { - if ($nb < 1) $nb = 1; + if ($nb < 1) { + $nb = 1; + } $q = $this->createQueryBuilder('n') ->orderBy('n.id', 'DESC') diff --git a/src/InsaLan/NewsBundle/Entity/Slider.php b/src/InsaLan/NewsBundle/Entity/Slider.php index 81dcd93e..6685f9ce 100644 --- a/src/InsaLan/NewsBundle/Entity/Slider.php +++ b/src/InsaLan/NewsBundle/Entity/Slider.php @@ -162,8 +162,7 @@ public function onPostUpdate() public function onPreRemove() { $name = Slider::UPLOAD_PATH.DIRECTORY_SEPARATOR.$this->getId().'.png'; - if (file_exists($name)) - { + if (file_exists($name)) { unlink($name); } } diff --git a/src/InsaLan/NewsBundle/Entity/SliderRepository.php b/src/InsaLan/NewsBundle/Entity/SliderRepository.php index 4fb15990..f3ff28f6 100644 --- a/src/InsaLan/NewsBundle/Entity/SliderRepository.php +++ b/src/InsaLan/NewsBundle/Entity/SliderRepository.php @@ -14,7 +14,9 @@ class SliderRepository extends EntityRepository { public function getLatest($nb) { - if ($nb < 1) $nb = 1; + if ($nb < 1) { + $nb = 1; + } $q = $this->createQueryBuilder('s') ->orderBy('s.id', 'DESC') diff --git a/src/InsaLan/PizzaBundle/Controller/AdminController.php b/src/InsaLan/PizzaBundle/Controller/AdminController.php index f2c1f162..1b053726 100644 --- a/src/InsaLan/PizzaBundle/Controller/AdminController.php +++ b/src/InsaLan/PizzaBundle/Controller/AdminController.php @@ -17,14 +17,17 @@ class AdminController extends Controller * @Route("/admin/{id}") * @Template() */ - public function indexAction($id = null) { + public function indexAction($id = null) + { $em = $this->getDoctrine()->getManager(); $order = $formAdd = null; $orders = $em->getRepository('InsaLanPizzaBundle:Order')->getAll(); $ordersChoices = array(null => ""); - foreach($orders as $o) { - if ($o->getDelivery()->getTimestamp() < mktime() - 3600*24*7) continue; + foreach ($orders as $o) { + if ($o->getDelivery()->getTimestamp() < mktime() - 3600*24*7) { + continue; + } $ordersChoices[$o->getId()] = "Le " . $o->getDelivery()->format("d/m à H:i") . " ~ " . ($o->getCapacity() - $o->getAvailableOrders(false, false)) . " commandes sur " @@ -42,25 +45,28 @@ public function indexAction($id = null) { $data = $form->getData(); return $this->redirect($this->generateUrl( 'insalan_pizza_admin_index_1', - array('id' => $data['order']))); + array('id' => $data['order']) + )); } - if($id) { - + if ($id) { $order = $em->getRepository('InsaLanPizzaBundle:Order')->getOneById($id); - if(!$order) + if (!$order) { throw new \Exception("Not Available"); + } $form->get('order')->submit($order->getId()); $pizzas = array(); $sum = 0; foreach ($order->getOrders() as $uo) { - if(!$uo->getPaymentDone(true)) + if (!$uo->getPaymentDone(true)) { continue; - if (!isset($pizzas[$uo->getPizza()->getName()])) + } + if (!isset($pizzas[$uo->getPizza()->getName()])) { $pizzas[$uo->getPizza()->getName()] = 0; + } $pizzas[$uo->getPizza()->getName()]++; $sum += $uo->getPizza()->getPrice(); } @@ -68,7 +74,6 @@ public function indexAction($id = null) { $order->sum = $sum; $formAdd = $this->getAddUserOrderForm($order)->createView(); - } return array('order' => $order, 'form' => $form->createView(), 'formAdd' => $formAdd); @@ -78,7 +83,8 @@ public function indexAction($id = null) { * @Route("/admin/{id}/add") * @Method({"POST"}) */ - public function addAction(Entity\Order $order) { + public function addAction(Entity\Order $order) + { $em = $this->getDoctrine()->getManager(); @@ -98,22 +104,23 @@ public function addAction(Entity\Order $order) { $uo->setPrice($data['price']); $user = $em->getRepository("InsaLanUserBundle:User")->findOneByUsername($data['username']); - if($user) + if ($user) { $uo->setUser($user); + } $em->persist($uo); $em->flush(); } return $this->redirect($this->generateUrl("insalan_pizza_admin_index_1", array("id" => $order->getId()))); - } /** * @Route("/admin/{id}/lock") * @Method({"POST"}) */ - public function lockAction(Entity\Order $order) { + public function lockAction(Entity\Order $order) + { $em = $this->getDoctrine()->getManager(); $order->setClosed(true); $em->persist($order); @@ -125,7 +132,8 @@ public function lockAction(Entity\Order $order) { * @Route("/admin/{id}/unlock") * @Method({"POST"}) */ - public function unlockAction(Entity\Order $order) { + public function unlockAction(Entity\Order $order) + { $em = $this->getDoctrine()->getManager(); $order->setClosed(false); $em->persist($order); @@ -137,7 +145,8 @@ public function unlockAction(Entity\Order $order) { * @Route("/admin/order/{id}/remove") * @Method({"POST"}) */ - public function order_removeAction(Entity\UserOrder $uo) { + public function order_removeAction(Entity\UserOrder $uo) + { $em = $this->getDoctrine()->getManager(); @@ -153,7 +162,8 @@ public function order_removeAction(Entity\UserOrder $uo) { * @Route("/admin/order/{id}/status/{status}") * @Method({"POST"}) */ - public function order_statusAction(Entity\UserOrder $uo, $status) { + public function order_statusAction(Entity\UserOrder $uo, $status) + { $em = $this->getDoctrine()->getManager(); @@ -164,19 +174,19 @@ public function order_statusAction(Entity\UserOrder $uo, $status) { $em->flush(); return new JsonResponse(array("err" => null)); - } /////////////// PRIVATE ////////// - private function getAddUserOrderForm(Entity\Order $o) { + private function getAddUserOrderForm(Entity\Order $o) + { $em = $this->getDoctrine()->getManager(); $pizzas = $em->getRepository('InsaLanPizzaBundle:Pizza')->findAll(); $pizzasChoices = array(); - foreach($pizzas as $pizza) { + foreach ($pizzas as $pizza) { $pizzasChoices[$pizza->getId()] = $pizza->getName() . " (" . $pizza->getPrice() . " €)"; } @@ -193,5 +203,4 @@ private function getAddUserOrderForm(Entity\Order $o) { ->setAction($this->generateUrl('insalan_pizza_admin_add', array('id' => $o->getId()))) ->getForm(); } - } diff --git a/src/InsaLan/PizzaBundle/Controller/DefaultController.php b/src/InsaLan/PizzaBundle/Controller/DefaultController.php index 68b0696c..e9f7cea0 100644 --- a/src/InsaLan/PizzaBundle/Controller/DefaultController.php +++ b/src/InsaLan/PizzaBundle/Controller/DefaultController.php @@ -35,17 +35,18 @@ public function indexAction() $ordersChoices = array(); - foreach($orders as $order) { + foreach ($orders as $order) { $a = 10*round($order->getAvailableOrders() / 10); - if($a <= 0) + if ($a <= 0) { $a = 10; + } $ordersChoices[$order->getId()] = "Le " . $order->getDelivery()->format("d/m à H \h i") . " (moins de " . $a . " pizzas disponibles)"; } $pizzasChoices = array(); - foreach($pizzas as $pizza) { + foreach ($pizzas as $pizza) { $pizzasChoices[$pizza->getId()] = $pizza->getName() . " (" . $pizza->getPrice() . " € + " . $paypalIncrease . " €)"; } @@ -56,8 +57,7 @@ public function indexAction() ->getForm(); $form->handleRequest($this->getRequest()); - if($form->isValid()) { - + if ($form->isValid()) { $data = $form->getData(); $order = $em->getRepository('InsaLanPizzaBundle:Order')->findOneById($data["order"]); @@ -89,16 +89,17 @@ public function indexAction() /** * @Route("/validate/{id}") */ - public function validateAction(Entity\UserOrder $userOrder) { + public function validateAction(Entity\UserOrder $userOrder) + { $em = $this->getDoctrine()->getManager(); $payment = $this->get("insalan.user.payment"); - if($payment->check($this->getRequest(), true)) { + if ($payment->check($this->getRequest(), true)) { $userOrder->setPaymentDone(true); $em->persist($userOrder); $hour = $userOrder->getOrder()->getDelivery()->format("H \h i"); - $this->get('session')->getFlashBag()->add('info', "Commande réalisée avec succès ! Votre pizza sera livrée vers $hour." ); + $this->get('session')->getFlashBag()->add('info', "Commande réalisée avec succès ! Votre pizza sera livrée vers $hour."); } else { $em->remove($userOrder); $this->get('session')->getFlashBag()->add('error', "Erreur de paiement. En cas de problème, veuillez contacter un membre du staff rapidement."); @@ -107,6 +108,5 @@ public function validateAction(Entity\UserOrder $userOrder) { $em->flush(); return $this->redirect($this->generateUrl("insalan_pizza_default_index")); - } } diff --git a/src/InsaLan/PizzaBundle/DataFixtures/ORM/OrderLoader.php b/src/InsaLan/PizzaBundle/DataFixtures/ORM/OrderLoader.php index d6c0f297..eb5c097b 100644 --- a/src/InsaLan/PizzaBundle/DataFixtures/ORM/OrderLoader.php +++ b/src/InsaLan/PizzaBundle/DataFixtures/ORM/OrderLoader.php @@ -7,7 +7,8 @@ use InsaLan\PizzaBundle\Entity\Order; class OrderLoader extends AbstractFixture implements OrderedFixtureInterface -{ +{ + public function getOrder() { @@ -15,7 +16,7 @@ public function getOrder() } public function load(ObjectManager $manager) - { + { $h1 = new \Datetime(); $h2 = new \Datetime(); @@ -42,4 +43,4 @@ public function load(ObjectManager $manager) $manager->flush(); } -} \ No newline at end of file +} diff --git a/src/InsaLan/PizzaBundle/DataFixtures/ORM/PizzaLoader.php b/src/InsaLan/PizzaBundle/DataFixtures/ORM/PizzaLoader.php index c3071ca6..b6e7dad1 100644 --- a/src/InsaLan/PizzaBundle/DataFixtures/ORM/PizzaLoader.php +++ b/src/InsaLan/PizzaBundle/DataFixtures/ORM/PizzaLoader.php @@ -7,7 +7,8 @@ use InsaLan\PizzaBundle\Entity\Pizza; class PizzaLoader extends AbstractFixture implements OrderedFixtureInterface -{ +{ + public function getOrder() { @@ -39,4 +40,4 @@ public function load(ObjectManager $manager) $manager->flush(); } -} \ No newline at end of file +} diff --git a/src/InsaLan/PizzaBundle/DataFixtures/ORM/UserOrderLoader.php b/src/InsaLan/PizzaBundle/DataFixtures/ORM/UserOrderLoader.php index c507a0d2..0d4e890a 100644 --- a/src/InsaLan/PizzaBundle/DataFixtures/ORM/UserOrderLoader.php +++ b/src/InsaLan/PizzaBundle/DataFixtures/ORM/UserOrderLoader.php @@ -7,7 +7,8 @@ use InsaLan\PizzaBundle\Entity\UserOrder; class UserOrderLoader extends AbstractFixture implements OrderedFixtureInterface -{ +{ + public function getOrder() { @@ -15,7 +16,7 @@ public function getOrder() } public function load(ObjectManager $manager) - { + { // Web Users @@ -64,4 +65,4 @@ public function load(ObjectManager $manager) $manager->flush(); } -} \ No newline at end of file +} diff --git a/src/InsaLan/PizzaBundle/Entity/Order.php b/src/InsaLan/PizzaBundle/Entity/Order.php index 560fdb08..1e761674 100644 --- a/src/InsaLan/PizzaBundle/Entity/Order.php +++ b/src/InsaLan/PizzaBundle/Entity/Order.php @@ -47,12 +47,12 @@ class Order protected $foreignCapacity; /** - * @ORM\Column(type="datetime") + * @ORM\Column(type="datetime") */ protected $createdAt; /** - * @ORM\Column(type="datetime") + * @ORM\Column(type="datetime") */ protected $updatedAt; @@ -75,23 +75,26 @@ public function __construct() /** * Get available number of pizzas (virtual) */ - public function getAvailableOrders($foreign = false, $noNegative = true) { + public function getAvailableOrders($foreign = false, $noNegative = true) + { $qty = 0; $qtyForeign = 0; - foreach($this->getOrders() as $uo) { - if($uo->getPaymentDone()) { + foreach ($this->getOrders() as $uo) { + if ($uo->getPaymentDone()) { $qty++; - if($uo->getForeign()) + if ($uo->getForeign()) { $qtyForeign++; + } } } $globalCapacity = $this->getCapacity() - $qty; $foreignCapacity = $this->getForeignCapacity() - $qtyForeign; - if($foreign) + if ($foreign) { $capacity = min($globalCapacity, $foreignCapacity); - else + } else { $capacity = $globalCapacity; + } return $capacity < 0 && $noNegative ? 0 : $capacity; } @@ -99,7 +102,8 @@ public function getAvailableOrders($foreign = false, $noNegative = true) { /** * Get an ordered array of userOrders */ - public function getOrdersOrdered() { + public function getOrdersOrdered() + { $userOrders = $this->orders->toArray(); usort($userOrders, array('InsaLan\PizzaBundle\Entity\UserOrder','cmp')); return $userOrders; @@ -109,11 +113,13 @@ public function getOrdersOrdered() { * Date utils */ - public function isDelivered() { + public function isDelivered() + { return new \Datetime() > $this->delivery; } - public function isExpired() { + public function isExpired() + { return new \Datetime() > $this->expiration; } @@ -246,7 +252,7 @@ public function setCreatedAt($createdAt) /** * Get createdAt * - * @return \DateTime + * @return \DateTime */ public function getCreatedAt() { @@ -269,7 +275,7 @@ public function setUpdatedAt($updatedAt) /** * Get updatedAt * - * @return \DateTime + * @return \DateTime */ public function getUpdatedAt() { @@ -293,7 +299,7 @@ public function setClosed($closed) /** * Get closed * - * @return boolean + * @return boolean */ public function getClosed() { @@ -316,7 +322,7 @@ public function setForeignCapacity($foreignCapacity) /** * Get foreignCapacity * - * @return integer + * @return integer */ public function getForeignCapacity() { diff --git a/src/InsaLan/PizzaBundle/Entity/OrderRepository.php b/src/InsaLan/PizzaBundle/Entity/OrderRepository.php index e2ab7a8a..c1f106fa 100644 --- a/src/InsaLan/PizzaBundle/Entity/OrderRepository.php +++ b/src/InsaLan/PizzaBundle/Entity/OrderRepository.php @@ -6,9 +6,11 @@ use InsaLan\UserBundle\Entity\User; class OrderRepository extends EntityRepository -{ +{ - public function getOneById($id) { + + public function getOneById($id) + { $q = $this->createQueryBuilder('o') ->leftJoin('o.orders', 'uo') @@ -23,7 +25,6 @@ public function getOneById($id) { ; return $q->getQuery()->getSingleResult(); - } public function getAvailable(User $user) @@ -44,12 +45,13 @@ public function getAvailable(User $user) $foreign = $this->isForeignUser($user); $out = array(); - foreach($q->getQuery()->execute() as $order) { - if($order->getAvailableOrders($foreign) > 0) $out[] = $order; + foreach ($q->getQuery()->execute() as $order) { + if ($order->getAvailableOrders($foreign) > 0) { + $out[] = $order; + } } return $out; - } public function getAll() diff --git a/src/InsaLan/PizzaBundle/Entity/Pizza.php b/src/InsaLan/PizzaBundle/Entity/Pizza.php index a171091a..87120070 100644 --- a/src/InsaLan/PizzaBundle/Entity/Pizza.php +++ b/src/InsaLan/PizzaBundle/Entity/Pizza.php @@ -33,14 +33,15 @@ class Pizza protected $description; - public function __toString() { + public function __toString() + { return $this->getName(); } /** * Get id * - * @return integer + * @return integer */ public function getId() { @@ -63,7 +64,7 @@ public function setName($name) /** * Get name * - * @return string + * @return string */ public function getName() { @@ -86,7 +87,7 @@ public function setPrice($price) /** * Get price * - * @return float + * @return float */ public function getPrice() { @@ -109,7 +110,7 @@ public function setDescription($description) /** * Get description * - * @return string + * @return string */ public function getDescription() { diff --git a/src/InsaLan/PizzaBundle/Entity/UserOrder.php b/src/InsaLan/PizzaBundle/Entity/UserOrder.php index 72e9ea19..4f6f82b6 100644 --- a/src/InsaLan/PizzaBundle/Entity/UserOrder.php +++ b/src/InsaLan/PizzaBundle/Entity/UserOrder.php @@ -25,7 +25,7 @@ class UserOrder public static function cmp($a, $b) { $c = strcasecmp($a->getUsername(), $b->getUsername()); - if($c === 0) { + if ($c === 0) { $c = strcasecmp($a->getFullname(), $b->getFullname()); } return $c; @@ -101,28 +101,34 @@ public static function cmp($a, $b) */ protected $updatedAt; - public function __construct() { + public function __construct() + { $this->paymentDone = false; $this->createdAt = $this->updatedAt = new \DateTime(); $this->price = self::FULL_PRICE; $this->foreign = false; } - public function getUsername() { - if($this->user) + public function getUsername() + { + if ($this->user) { return $this->user->getUsername(); - else + } else { return $this->usernameCanonical; + } } - public function getFullname() { - if($this->user) + public function getFullname() + { + if ($this->user) { return $this->user->getFirstName() . " " . $this->user->getLastName(); - else + } else { return $this->fullnameCanonical; + } } - public function __toString() { + public function __toString() + { return "Commande #" . $this->getId(); } diff --git a/src/InsaLan/PizzaBundle/Entity/UserOrderRepository.php b/src/InsaLan/PizzaBundle/Entity/UserOrderRepository.php index 8e6442ae..1598a3e7 100644 --- a/src/InsaLan/PizzaBundle/Entity/UserOrderRepository.php +++ b/src/InsaLan/PizzaBundle/Entity/UserOrderRepository.php @@ -7,7 +7,8 @@ class UserOrderRepository extends EntityRepository { - public function getByUser(\InsaLan\UserBundle\Entity\User $user) { + public function getByUser(\InsaLan\UserBundle\Entity\User $user) + { $q = $this->createQueryBuilder('uo') ->leftJoin('uo.order', 'o') @@ -24,5 +25,4 @@ public function getByUser(\InsaLan\UserBundle\Entity\User $user) { return $q->getQuery()->execute(); } - } diff --git a/src/InsaLan/TournamentBundle/Admin/GroupAdmin.php b/src/InsaLan/TournamentBundle/Admin/GroupAdmin.php index 1dc00e21..2d0b7f5a 100644 --- a/src/InsaLan/TournamentBundle/Admin/GroupAdmin.php +++ b/src/InsaLan/TournamentBundle/Admin/GroupAdmin.php @@ -39,7 +39,7 @@ protected function configureListFields(ListMapper $listMapper) ->addIdentifier('name') ->add('stage') ->add("Participants", null, array("template" => "InsaLanTournamentBundle:Admin:admin_extra_infos.html.twig")) - ->add('_action','actions',array('actions' => array('edit' => array(),'show' => array()))); + ->add('_action', 'actions', array('actions' => array('edit' => array(),'show' => array()))); ; } @@ -80,36 +80,30 @@ public function prePersist($group) } private function autoManageMatches($group) - { + { $em = $this->getConfigurationPool()->getContainer()->get('Doctrine')->getManager(); // Clean up deprecated matches - foreach($group->getMatches()->toArray() as $match) { - - if(!$group->hasParticipant($match->getPart1()) || + foreach ($group->getMatches()->toArray() as $match) { + if (!$group->hasParticipant($match->getPart1()) || !$group->hasParticipant($match->getPart2())) { - $group->removeMatch($match); $em->remove($match); - } } - // Create missing matches + // Create missing matches $participants = $group->getParticipants()->getValues(); - for($i = 0; $i < count($participants); $i++) - { - for($j = $i+1; $j < count($participants); $j++) - { - + for ($i = 0; $i < count($participants); $i++) { + for ($j = $i+1; $j < count($participants); $j++) { $a = $participants[$i]; $b = $participants[$j]; - if(!$group->getMatchBetween($a, $b)) { + if (!$group->getMatchBetween($a, $b)) { $match = new Match(); $match->setPart1($a); $match->setPart2($b); @@ -118,9 +112,7 @@ private function autoManageMatches($group) $group->addMatch($match); $em->persist($match); } - } } - } } diff --git a/src/InsaLan/TournamentBundle/Admin/ManagerAdmin.php b/src/InsaLan/TournamentBundle/Admin/ManagerAdmin.php index 6da5f877..d2a5ec55 100644 --- a/src/InsaLan/TournamentBundle/Admin/ManagerAdmin.php +++ b/src/InsaLan/TournamentBundle/Admin/ManagerAdmin.php @@ -46,5 +46,4 @@ protected function configureListFields(ListMapper $listMapper) ->add('arrived') ; } - } diff --git a/src/InsaLan/TournamentBundle/Admin/MatchAdmin.php b/src/InsaLan/TournamentBundle/Admin/MatchAdmin.php index d87d3a8f..d878483c 100644 --- a/src/InsaLan/TournamentBundle/Admin/MatchAdmin.php +++ b/src/InsaLan/TournamentBundle/Admin/MatchAdmin.php @@ -12,7 +12,8 @@ use InsaLan\TournamentBundle\Entity\Match; class MatchAdmin extends Admin -{ +{ + protected $stateDef = array( Match::STATE_UPCOMING => 'En attente', @@ -69,12 +70,15 @@ protected function configureListFields(ListMapper $listMapper) ->add('part1', null, array('label' => "Participant 1")) ->add('part2', null, array('label' => "Participant 2")) ->add('extraInfos', null, array('label' => "Conteneur")) - ->add('_action','actions', + ->add( + '_action', + 'actions', array('actions' => array('view' => array(), 'edit' => array(), 'createRound' => array( 'template' => 'InsaLanTournamentBundle:Admin:list__action_create_round.html.twig' - )))) + ))) + ) ; } @@ -85,25 +89,24 @@ protected function configureRoutes(RouteCollection $collection) public function postUpdate($match) { - if($match->getState() === Match::STATE_FINISHED && $match->getKoMatch()) - { + if ($match->getState() === Match::STATE_FINISHED && $match->getKoMatch()) { $em = $this->getConfigurationPool()->getContainer()->get('Doctrine')->getManager(); $repository = $em->getRepository('InsaLanTournamentBundle:KnockoutMatch'); $repository->propagateVictory($match->getKoMatch()); $ko = $match->getKoMatch()->getKnockout(); - if($ko->getDoubleElimination()) { + if ($ko->getDoubleElimination()) { // deal with it. $repository->propagateFromNode( $repository ->getRoot($ko) ->getChildren() - ->get(1)); // only update the hard part of the tree + ->get(1) + ); // only update the hard part of the tree } $em->flush(); } } - } diff --git a/src/InsaLan/TournamentBundle/Admin/PlayerAdmin.php b/src/InsaLan/TournamentBundle/Admin/PlayerAdmin.php index 2b5d0ee0..c1554400 100644 --- a/src/InsaLan/TournamentBundle/Admin/PlayerAdmin.php +++ b/src/InsaLan/TournamentBundle/Admin/PlayerAdmin.php @@ -57,5 +57,4 @@ protected function configureListFields(ListMapper $listMapper) ->add('arrived') ; } - } diff --git a/src/InsaLan/TournamentBundle/Admin/RoundAdmin.php b/src/InsaLan/TournamentBundle/Admin/RoundAdmin.php index 14455571..d9a4cf48 100644 --- a/src/InsaLan/TournamentBundle/Admin/RoundAdmin.php +++ b/src/InsaLan/TournamentBundle/Admin/RoundAdmin.php @@ -24,12 +24,12 @@ protected function configureFormFields(FormMapper $formMapper) } protected function configureShowFields(ShowMapper $showMapper) - { + { $showMapper ->add("Détails", null, array("template" => "InsaLanTournamentBundle:Admin:admin_extra_infos.html.twig")) - ->add('match', null, array('route' => array('name' => 'show'))) - ->add('score1', null, array('label' => "Score 1")) - ->add('score2', null, array('label' => "Score 2")) + ->add('match', null, array('route' => array('name' => 'show'))) + ->add('score1', null, array('label' => "Score 1")) + ->add('score2', null, array('label' => "Score 2")) ->add('fullReplay', "string", array('label' => "Replay")) ; } @@ -49,24 +49,21 @@ protected function configureListFields(ListMapper $listMapper) $listMapper ->add('match.part1', null, array('label' => "Participant 1")) ->add('match.part2', null, array('label' => "Participant 2")) - ->add('score1', null, array('label' => "Score 1")) - ->add('score2', null, array('label' => "Score 2")) - ->add('_action','actions',array('actions' => array('edit' => array()))); + ->add('score1', null, array('label' => "Score 1")) + ->add('score2', null, array('label' => "Score 2")) + ->add('_action', 'actions', array('actions' => array('edit' => array()))); ; } public function postUpdate($round) - { + { $match = $round->getMatch(); - if($match->getState() === Match::STATE_FINISHED && $match->getKoMatch()) - { + if ($match->getState() === Match::STATE_FINISHED && $match->getKoMatch()) { $em = $this->getConfigurationPool()->getContainer()->get('Doctrine')->getManager(); $repository = $em->getRepository('InsaLanTournamentBundle:KnockoutMatch'); $repository->propagateVictory($match->getKoMatch()); $em->flush(); } } - - } diff --git a/src/InsaLan/TournamentBundle/Admin/TeamAdmin.php b/src/InsaLan/TournamentBundle/Admin/TeamAdmin.php index bd02a4f7..149d7c0d 100644 --- a/src/InsaLan/TournamentBundle/Admin/TeamAdmin.php +++ b/src/InsaLan/TournamentBundle/Admin/TeamAdmin.php @@ -24,8 +24,8 @@ protected function configureFormFields(FormMapper $formMapper) 'required' => true, 'choices' => array( 0 => 'Équipe incomplète', - 1 => 'Dans la liste d\'attente', - 2 => 'Validée' + 1 => 'Dans la liste d\'attente', + 2 => 'Validée' ) )) ->add('plainPassword', 'repeated', array( diff --git a/src/InsaLan/TournamentBundle/Admin/TournamentAdmin.php b/src/InsaLan/TournamentBundle/Admin/TournamentAdmin.php index 6833c92c..3508dad9 100644 --- a/src/InsaLan/TournamentBundle/Admin/TournamentAdmin.php +++ b/src/InsaLan/TournamentBundle/Admin/TournamentAdmin.php @@ -51,14 +51,14 @@ protected function configureFormFields(FormMapper $formMapper) 'manual' => 'Autre/Manuel'), 'required' => true)) ->add('file', 'file', array('required' => false)) - ->add('loginType','choice', array( - 'choices' => array( - 'other' => 'Autre', - 'Steam' => 'Steam', - 'battlenet' => 'BattleNet' - ), - 'required' => true - )) + ->add('loginType', 'choice', array( + 'choices' => array( + 'other' => 'Autre', + 'Steam' => 'Steam', + 'battlenet' => 'BattleNet' + ), + 'required' => true + )) ; } @@ -84,11 +84,13 @@ protected function configureListFields(ListMapper $listMapper) ; } - public function prePersist($e) { + public function prePersist($e) + { $e->upload(); } - public function preUpdate($e) { + public function preUpdate($e) + { $this->prePersist($e); } } diff --git a/src/InsaLan/TournamentBundle/Controller/AdminController.php b/src/InsaLan/TournamentBundle/Controller/AdminController.php index 35b1bc18..fbedb338 100644 --- a/src/InsaLan/TournamentBundle/Controller/AdminController.php +++ b/src/InsaLan/TournamentBundle/Controller/AdminController.php @@ -50,9 +50,9 @@ public function indexAction($id = null) $data = $form->getData(); return $this->redirect($this->generateUrl( 'insalan_tournament_admin_index_1', - array('id' => $data['tournament']))); - } - else if (null !== $id) { + array('id' => $data['tournament']) + )); + } elseif (null !== $id) { /** Print Tournament informations **/ @@ -67,7 +67,8 @@ public function indexAction($id = null) } if (null === $tournament) { - throw new NotFoundHttpException('InsaLan\\TournamentBundle\\Entity\\Tournament object not found.');; + throw new NotFoundHttpException('InsaLan\\TournamentBundle\\Entity\\Tournament object not found.'); + ; } @@ -90,7 +91,6 @@ public function indexAction($id = null) } $formKo = $this->getFormKo($data['tournament']); - } @@ -102,7 +102,7 @@ public function indexAction($id = null) 'players' => $players ); - if($formKo) { + if ($formKo) { $output['formKo'] = $formKo->createView(); } @@ -122,7 +122,7 @@ public function player_tooglePaymentAction(Entity\Tournament $t, Entity\Player $ $em->persist($p); $em->flush(); - return new JsonResponse(array("err" => null)); + return new JsonResponse(array("err" => null)); } /** @@ -138,7 +138,7 @@ public function player_toogleArrivedAction(Entity\Tournament $t, Entity\Player $ $em->persist($p); $em->flush(); - return new JsonResponse(array("err" => null)); + return new JsonResponse(array("err" => null)); } /** @@ -154,7 +154,7 @@ public function manager_tooglePaymentAction(Entity\Tournament $t, Entity\Manager $em->persist($m); $em->flush(); - return new JsonResponse(array("err" => null)); + return new JsonResponse(array("err" => null)); } /** @@ -184,7 +184,6 @@ public function stageAction(Entity\GroupStage $g) $matches = $em->getRepository("InsaLanTournamentBundle:Match")->getByGroupStage($g); return array("stage" => $g, "matches" => $matches); - } /** @@ -197,7 +196,6 @@ public function knockoutAction(Entity\Knockout $k) $matches = $em->getRepository("InsaLanTournamentBundle:Match")->getByKnockout($k); return array("knockout" => $k, "matches" => $matches); - } /** @@ -208,10 +206,11 @@ public function match_setStateAction(Entity\Match $m, $state) $em = $this->getDoctrine()->getManager(); $state = intval($state); - if($state !== Entity\Match::STATE_UPCOMING && + if ($state !== Entity\Match::STATE_UPCOMING && $state !== Entity\Match::STATE_ONGOING && - $state !== Entity\Match::STATE_FINISHED) + $state !== Entity\Match::STATE_FINISHED) { throw new ControllerException("Unexpected argument state"); + } $m->setState($state); $this->updateMatch($m); @@ -219,7 +218,6 @@ public function match_setStateAction(Entity\Match $m, $state) $em->flush(); return $this->getReturnRedirect($m); - } /** @@ -228,8 +226,9 @@ public function match_setStateAction(Entity\Match $m, $state) public function match_addRoundAction(Entity\Match $m) { $request = $this->get('request'); - if($request->getMethod() !== "POST") + if ($request->getMethod() !== "POST") { throw new ControllerException("Bad method"); + } $score1 = intval($request->get('score1')); $score2 = intval($request->get('score2')); @@ -255,7 +254,7 @@ public function match_resetAction(Entity\Match $m) { $em = $this->getDoctrine()->getManager(); - foreach($m->getRounds() as $r) { + foreach ($m->getRounds() as $r) { $m->removeRound($r); $em->remove($r); } @@ -273,13 +272,15 @@ public function create_koAction(Entity\Tournament $tournament) $form = $this->getFormKo($tournament->getId()); $form->handleRequest($this->getRequest()); - if(!$form->isValid()) + if (!$form->isValid()) { throw new ControllerException("Not allowed"); + } $data = $form->getData(); - if($data['size'] <= 1) + if ($data['size'] <= 1) { throw new ControllerException("Not allowed"); + } $em = $this->getDoctrine()->getManager(); @@ -293,8 +294,9 @@ public function create_koAction(Entity\Tournament $tournament) ->generateMatches($ko, $data['size'], $data['double']); return $this->redirect($this->generateUrl( - 'insalan_tournament_admin_knockout_view', - array('id' => $ko->getId()))); + 'insalan_tournament_admin_knockout_view', + array('id' => $ko->getId()) + )); } /** @@ -308,16 +310,14 @@ public function knockout_viewAction(Entity\Knockout $ko) $depth = $em->getRepository('InsaLanTournamentBundle:KnockoutMatch')->getLeftDepth($ko); $children = pow(2, $depth + ($ko->getDoubleElimination() ? 0 : 1)); - if($this->get('request')->getMethod() === "POST") { - + if ($this->get('request')->getMethod() === "POST") { $root = $em->getRepository('InsaLanTournamentBundle:KnockoutMatch')->getRoot($ko); - if($ko->getDoubleElimination()) { + if ($ko->getDoubleElimination()) { $root = $root->getChildren()->get(0); } $koMatches = $em->getRepository('InsaLanTournamentBundle:KnockoutMatch')->getLvlChildren($root, $depth); - for($i = 0; $i < $children / 2; $i++) { - + for ($i = 0; $i < $children / 2; $i++) { $part1 = $this->get('request')->request->get("participant_".($i*2+1)); $part2 = $this->get('request')->request->get("participant_".($i*2+2)); @@ -327,10 +327,9 @@ public function knockout_viewAction(Entity\Knockout $ko) // Is there any previous match ? $km = $koMatches[$i]; - if($km->getMatch()) { + if ($km->getMatch()) { $match = $km->getMatch(); - } - else { + } else { $match = new Entity\Match(); $match->setState(Entity\Match::STATE_UPCOMING); $km->setMatch($match); @@ -342,14 +341,12 @@ public function knockout_viewAction(Entity\Knockout $ko) $em->persist($km); $em->persist($match); - } // Propagate for potential empty matches $em->getRepository('InsaLanTournamentBundle:KnockoutMatch')->propagateVictoryAll($ko); $em->flush(); - } $ko->jsonData = $em->getRepository('InsaLanTournamentBundle:KnockoutMatch')->getJson($ko); @@ -369,10 +366,12 @@ public function knockout_viewAction(Entity\Knockout $ko) } - private function updateMatch(Entity\Match $match) { + private function updateMatch(Entity\Match $match) + { - if($match->getState() !== Entity\Match::STATE_FINISHED || !$match->getKoMatch()) + if ($match->getState() !== Entity\Match::STATE_FINISHED || !$match->getKoMatch()) { return; + } $em = $this->getDoctrine()->getManager(); @@ -381,36 +380,42 @@ private function updateMatch(Entity\Match $match) { $ko = $match->getKoMatch()->getKnockout(); - if($ko->getDoubleElimination()) { + if ($ko->getDoubleElimination()) { // deal with it. $repository->propagateFromNode( $repository ->getRoot($ko) ->getChildren() - ->get(1)); // only update the hard part of the tree + ->get(1) + ); // only update the hard part of the tree } - } - private function getFormKo($tournament) { + private function getFormKo($tournament) + { return $this->createFormBuilder() ->add('name', 'text', array("label" => "Nom")) ->add('size', 'integer', array("label" => "Taille", "precision" => 0)) ->add('double', 'checkbox', array("label" => "Double Elimination", "required" => false)) - ->setAction($this->generateUrl('insalan_tournament_admin_create_ko', - array('id' => $tournament))) + ->setAction($this->generateUrl( + 'insalan_tournament_admin_create_ko', + array('id' => $tournament) + )) ->getForm(); } - private function getReturnRedirect(Entity\Match $m) { - if($m->getKoMatch()) { + private function getReturnRedirect(Entity\Match $m) + { + if ($m->getKoMatch()) { return $this->redirect($this->generateUrl( 'insalan_tournament_admin_knockout', - array('id' => $m->getKoMatch()->getKnockout()->getId()))); + array('id' => $m->getKoMatch()->getKnockout()->getId()) + )); } return $this->redirect($this->generateUrl( - 'insalan_tournament_admin_stage', - array('id' => $m->getGroup()->getStage()->getId()))); + 'insalan_tournament_admin_stage', + array('id' => $m->getGroup()->getStage()->getId()) + )); } } diff --git a/src/InsaLan/TournamentBundle/Controller/CRUDController.php b/src/InsaLan/TournamentBundle/Controller/CRUDController.php index 7e346c9e..1a7d5b4c 100644 --- a/src/InsaLan/TournamentBundle/Controller/CRUDController.php +++ b/src/InsaLan/TournamentBundle/Controller/CRUDController.php @@ -34,5 +34,3 @@ public function createRoundAction() return new RedirectResponse($this->admin->generateUrl('list')); } } - -?> \ No newline at end of file diff --git a/src/InsaLan/TournamentBundle/Controller/DefaultController.php b/src/InsaLan/TournamentBundle/Controller/DefaultController.php index 49f9a022..529f0de4 100644 --- a/src/InsaLan/TournamentBundle/Controller/DefaultController.php +++ b/src/InsaLan/TournamentBundle/Controller/DefaultController.php @@ -34,14 +34,15 @@ public function indexAction() $future_tournaments = array(); foreach ($tournaments as $t) { - if($t->isOpenedNow()) // I can register ! + if ($t->isOpenedNow()) { // I can register ! $opened_tournaments[] = $t; - elseif ($t->isOpenedInFuture()) // tournament is not opened yet + } elseif ($t->isOpenedInFuture()) { // tournament is not opened yet $future_tournaments[] = $t; - elseif ($t->isClosed()) // tournament is past and closed + } elseif ($t->isClosed()) { // tournament is past and closed $old_tournaments[] = $t; - else // tournament is not completed yet, but I cannot register + } else { // tournament is not completed yet, but I cannot register $registration_closed_tournaments[] = $t; + } } return array('old_tournaments' => $old_tournaments, @@ -70,7 +71,7 @@ public function tournamentAction(Entity\Tournament $tournament) $output = array(); - foreach($KOs as $ko) { + foreach ($KOs as $ko) { $ko->jsonData = $em->getRepository('InsaLanTournamentBundle:KnockoutMatch')->getJson($ko); $output[] = $ko; } @@ -136,7 +137,7 @@ public function setCaptainAction(Request $request) ); } - foreach($team->getPlayers() as $player) { + foreach ($team->getPlayers() as $player) { if ($player->getId() == $player_id) { $team->setCaptain($player); $em->flush(); @@ -147,7 +148,6 @@ public function setCaptainAction(Request $request) throw $this->createNotFoundException( 'No user found for this id : '.$player_id ); - } /** @@ -163,7 +163,7 @@ public function matchDataAction($id) $group = $em->getRepository('InsaLanTournamentBundle:Group')->getById($match->getGroup()->getId(), false); $group->countWins(); - $scores = array_map(function($a) { + $scores = array_map(function ($a) { return $a['won'] * 3 + $a['draw'] * 2 + $a['lost']; }, $group->stats); @@ -210,14 +210,12 @@ public function knockoutAction(Entity\Tournament $t) $output = array(); - foreach($KOs as $ko) { + foreach ($KOs as $ko) { $ko->jsonData = $em->getRepository('InsaLanTournamentBundle:KnockoutMatch')->getJson($ko); $output[] = $ko; } return array("tournament" => $t, "knockouts" => $output); - - } /** @@ -237,18 +235,16 @@ public function teamDetailsAction(Entity\Participant $part) $grs = array(); // Populate and sort arrays - foreach($matches as $m) - { - if($m->getGroup() !== null) { + foreach ($matches as $m) { + if ($m->getGroup() !== null) { $id = $m->getGroup()->getId(); - if(!isset($grs[$id])) { + if (!isset($grs[$id])) { $grs[$id] = array(); } $grs[$id][] = $m; - } - elseif($m->getKoMatch() !== null) { + } elseif ($m->getKoMatch() !== null) { $id = $m->getKoMatch()->getKnockout()->getId(); - if(!isset($kos[$id])) { + if (!isset($kos[$id])) { $kos[$id] = array(); } $kos[$id][] = $m; @@ -258,21 +254,23 @@ public function teamDetailsAction(Entity\Participant $part) return array("part" => $part, "groupMatches" => $grs, "knockoutMatches" => $kos, "authorized" => $this->isUserInTeam($part)); } - private function isUserInTeam(Entity\Participant $part) { + private function isUserInTeam(Entity\Participant $part) + { $user = $this->get('security.context')->getToken()->getUser(); - if(!$user || $user === "anon.") return false; - - if($part instanceof Entity\Team) { + if (!$user || $user === "anon.") { + return false; + } + if ($part instanceof Entity\Team) { foreach ($part->getPlayers() as $p) { - if($p->getUser() && $p->getUser()->getId() === $user->getId()) + if ($p->getUser() && $p->getUser()->getId() === $user->getId()) { return true; + } } return false; } return $part->getUser() === $user; - } } diff --git a/src/InsaLan/TournamentBundle/Controller/ManagerController.php b/src/InsaLan/TournamentBundle/Controller/ManagerController.php index 58cc2497..b31aee96 100644 --- a/src/InsaLan/TournamentBundle/Controller/ManagerController.php +++ b/src/InsaLan/TournamentBundle/Controller/ManagerController.php @@ -45,7 +45,8 @@ class ManagerController extends Controller * Manage all steps for registering into a tournament as manager * @Route("/{tournament}/user/enroll") */ - public function enrollAction(Request $request, Entity\Tournament $tournament) { + public function enrollAction(Request $request, Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); @@ -54,14 +55,15 @@ public function enrollAction(Request $request, Entity\Tournament $tournament) { ->getRepository('InsaLanTournamentBundle:Manager') ->findOneByUserAndPendingTournament($usr, $tournament); - if ($manager === null) - return $this->redirect($this->generateUrl('insalan_tournament_manager_setname',array('tournament' => $tournament->getId()))); - else if ($tournament->getParticipantType() === 'team' && $manager->getParticipant() === null) - return $this->redirect($this->generateUrl('insalan_tournament_manager_jointeamwithpassword',array('tournament' => $tournament->getId()))); - else if (!$manager->getPaymentDone()) - return $this->redirect($this->generateUrl('insalan_tournament_manager_pay',array('tournament' => $tournament->getId()))); - else - return $this->redirect($this->generateUrl('insalan_tournament_manager_paydone',array('tournament' => $tournament->getId()))); + if ($manager === null) { + return $this->redirect($this->generateUrl('insalan_tournament_manager_setname', array('tournament' => $tournament->getId()))); + } elseif ($tournament->getParticipantType() === 'team' && $manager->getParticipant() === null) { + return $this->redirect($this->generateUrl('insalan_tournament_manager_jointeamwithpassword', array('tournament' => $tournament->getId()))); + } elseif (!$manager->getPaymentDone()) { + return $this->redirect($this->generateUrl('insalan_tournament_manager_pay', array('tournament' => $tournament->getId()))); + } else { + return $this->redirect($this->generateUrl('insalan_tournament_manager_paydone', array('tournament' => $tournament->getId()))); + } } /** @@ -78,7 +80,7 @@ public function setNameAction(Request $request, Entity\Tournament $tournament) // TODO Map managers like players into the tournament entity ? This will make counting easier $countManagers = count($em->getRepository('InsaLanTournamentBundle:Manager')->findByTournament($tournament)); - if($tournament->getMaxManager() != null && $countManagers >= $tournament->getMaxManager()) { + if ($tournament->getMaxManager() != null && $countManagers >= $tournament->getMaxManager()) { $this->get('session')->getFlashBag()->add('error', "Il ne reste plus de places manager sur ce tournois !"); return $this->redirect($this->generateUrl('insalan_tournament_user_index')); } @@ -96,14 +98,15 @@ public function setNameAction(Request $request, Entity\Tournament $tournament) $em->persist($manager); $em->flush(); - if($tournament->getParticipantType() === "team") + if ($tournament->getParticipantType() === "team") { return $this->redirect( $this->generateUrl('insalan_tournament_manager_jointeamwithpassword', array('tournament' => $tournament->getId())) ); - else // solo tournaments + } else { // solo tournaments return $this->redirect( $this->generateUrl('insalan_tournament_manager_joinsoloplayer', array('tournament' => $tournament->getId())) ); + } } return array('form' => $form->createView(), 'selectedGame' => $tournament->getType(), 'tournamentId' => $tournament->getId()); @@ -120,15 +123,17 @@ public function joinSoloPlayerAction(Request $request, Entity\Tournament $tourna $usr = $this->get('security.context')->getToken()->getUser(); // handle only solo tournaments - if($tournament->getParticipantType() !== "player") + if ($tournament->getParticipantType() !== "player") { throw new ControllerException("Joueurs solo non acceptées dans ce tournois"); + } // check if there is already a pending manager for this user and tournament $manager = $em->getRepository('InsaLanTournamentBundle:Manager') ->findOneByUserAndPendingTournament($usr, $tournament); - if($manager === null) + if ($manager === null) { return $this->redirect($this->generateUrl('insalan_tournament_manager_setname', array('tournament' => $tournament->getId()))); + } $form_player = new Player(); $form = $this->createForm(new SetPlayerName(), $form_player); // fill player gamename @@ -144,10 +149,12 @@ public function joinSoloPlayerAction(Request $request, Entity\Tournament $tourna 'gameName' => $form_player->getGameName(), 'tournament' => $tournament)); - if ($player === null) + if ($player === null) { throw new ControllerException("Joueur introuvable !"); - if ($player->getManager() != null) + } + if ($player->getManager() != null) { throw new ControllerException("Le joueur possède déjà un manager !"); + } $manager->setParticipant($player); $player->setManager($manager); @@ -156,11 +163,9 @@ public function joinSoloPlayerAction(Request $request, Entity\Tournament $tourna $em->flush(); return $this->redirect($this->generateUrl('insalan_tournament_manager_pay', array('tournament' => $tournament->getId()))); - } catch (ControllerException $e) { $error_details = $e->getMessage(); } - } return array('tournament' => $tournament, 'user' => $usr, 'manager' => $manager, 'error' => $error_details, 'form' => $form->createView()); } @@ -176,15 +181,17 @@ public function joinTeamWithPasswordAction(Request $request, Entity\Tournament $ $usr = $this->get('security.context')->getToken()->getUser(); // handle only team tournaments - if($tournament->getParticipantType() !== "team") + if ($tournament->getParticipantType() !== "team") { throw new ControllerException("Équipes non acceptées dans ce tournois"); + } // check if there is already a pending manager for this user and tournament $manager = $em->getRepository('InsaLanTournamentBundle:Manager') ->findOneByUserAndPendingTournament($usr, $tournament); - if($manager === null) + if ($manager === null) { return $this->redirect($this->generateUrl('insalan_tournament_manager_setname', array('tournament' => $tournament->getId()))); + } $form_team = new Team(); $form = $this->createForm(new TeamLoginType(), $form_team); // fill name and plainPassword @@ -202,15 +209,17 @@ public function joinTeamWithPasswordAction(Request $request, Entity\Tournament $ ->getRepository('InsaLanTournamentBundle:Team') ->findOneByNameAndTournament($form_team->getName(), $tournament); - if ($team === null || $team->getTournament()->getId() !== $tournament->getId()) + if ($team === null || $team->getTournament()->getId() !== $tournament->getId()) { throw new ControllerException("Équipe invalide"); + } $form_team->setPassword($encoder->encodePassword($form_team->getPlainPassword(), $team->getPasswordSalt())); if ($team->getPassword() === $form_team->getPassword()) { // denied if there is already a manager in the team - if ($team->getManager() != null) + if ($team->getManager() != null) { throw new ControllerException("L'équipe a déjà un manager"); + } // Because PHP don't support polymorphism, we must get the corresponding Participant object $team_participant = $em @@ -223,13 +232,12 @@ public function joinTeamWithPasswordAction(Request $request, Entity\Tournament $ $em->flush(); return $this->redirect($this->generateUrl('insalan_tournament_manager_pay', array('tournament' => $tournament->getId()))); - - } else + } else { throw new ControllerException("Mot de passe invalide"); + } } catch (ControllerException $e) { $error_details = $e->getMessage(); } - } return array('tournament' => $tournament, 'user' => $usr, 'manager' => $manager, 'error' => $error_details, 'form' => $form->createView()); } @@ -248,7 +256,8 @@ public function joinTeamWithToken() * @Route("/{tournament}/user/pay/details") * @Template() */ - public function payAction(Entity\Tournament $tournament) { + public function payAction(Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); @@ -256,7 +265,7 @@ public function payAction(Entity\Tournament $tournament) { ->getRepository('InsaLanTournamentBundle:Manager') ->findOneByUserAndPendingTournament($usr, $tournament); - if($tournament->isFree()) { + if ($tournament->isFree()) { $manager->setPaymentDone(true); $em->persist($manager); $em->flush(); @@ -270,7 +279,8 @@ public function payAction(Entity\Tournament $tournament) { * Paypal stuff * @Route("/{tournament}/user/pay/paypal_ec") */ - public function payPaypalECAction(Entity\Tournament $tournament) { + public function payPaypalECAction(Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); @@ -321,7 +331,8 @@ public function payPaypalECAction(Entity\Tournament $tournament) { * @Route("/{tournament}/user/pay/done") * @Template() */ - public function payDoneAction(Request $request, Entity\Tournament $tournament) { + public function payDoneAction(Request $request, Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); $manager = $em @@ -335,7 +346,8 @@ public function payDoneAction(Request $request, Entity\Tournament $tournament) { * Perform payment validation * @Route("/{tournament}/user/pay/done_temp") */ - public function payDoneTempAction(Request $request, Entity\Tournament $tournament) { + public function payDoneTempAction(Request $request, Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); $player = $em @@ -362,7 +374,8 @@ public function payDoneTempAction(Request $request, Entity\Tournament $tournamen * @Route("/{tournament}/user/pay/offline") * @Template() */ - public function payOfflineAction(Request $request, Entity\Tournament $tournament) { + public function payOfflineAction(Request $request, Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); $manager = $em @@ -377,7 +390,8 @@ public function payOfflineAction(Request $request, Entity\Tournament $tournament * TODO add flashbag confirmation * @Route("/{tournament}/user/leave") */ - public function leaveAction(Entity\Tournament $tournament) { + public function leaveAction(Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); @@ -385,17 +399,19 @@ public function leaveAction(Entity\Tournament $tournament) { ->getRepository('InsaLanTournamentBundle:Manager') ->findOneByUserAndPendingTournament($usr, $tournament); - if($manager->getTournament()->getParticipantType() !== "player") + if ($manager->getTournament()->getParticipantType() !== "player") { throw new ControllerException("Not Allowed"); // must be a player only tournament + } // not allowed if he paid something - if(!$tournament->isFree() && $manager->getPaymentDone()){ + if (!$tournament->isFree() && $manager->getPaymentDone()) { $this->get('session')->getFlashBag()->add('error', "Vous avez payé votre place, merci de contacter l'InsaLan si vous souhaitez vous désister."); return $this->redirect($this->generateUrl('insalan_tournament_user_index')); } // not allowed either if registration are closed - if(!$tournament->isOpenedNow()) + if (!$tournament->isOpenedNow()) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } $manager->getParticipant()->setManager(null); $manager->setParticipant(null); @@ -410,14 +426,16 @@ public function leaveAction(Entity\Tournament $tournament) { * TODO add flashbag confirmation * @Route("/user/leave/team/{teamId}") */ - public function leaveTeamAction($teamId) { + public function leaveTeamAction($teamId) + { $em = $this->getDoctrine()->getManager(); $team = $em ->getRepository('InsaLanTournamentBundle:Team') ->findOneById($teamId); - if($team === null) + if ($team === null) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } // get targeted manager $usr = $this->get('security.context')->getToken()->getUser(); @@ -426,17 +444,19 @@ public function leaveTeamAction($teamId) { ->findOneByUserAndPendingTournament($usr, $team->getTournament()); // is he part of the team roster ? - if($team->getManager() != $manager) + if ($team->getManager() != $manager) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } // not allowed if he paid something - if(!$team->getTournament()->isFree() && $manager->getPaymentDone()){ + if (!$team->getTournament()->isFree() && $manager->getPaymentDone()) { $this->get('session')->getFlashBag()->add('error', "Vous avez payé votre place, merci de contacter l'InsaLan si vous souhaitez vous désister."); return $this->redirect($this->generateUrl('insalan_tournament_user_index')); } // not allowed either if registration are closed - if(!$team->getTournament()->isOpenedNow()) + if (!$team->getTournament()->isOpenedNow()) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } $manager->setParticipant(null); $team->setManager(null); @@ -447,7 +467,4 @@ public function leaveTeamAction($teamId) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); } - } - -?> diff --git a/src/InsaLan/TournamentBundle/Controller/MerchantController.php b/src/InsaLan/TournamentBundle/Controller/MerchantController.php index c96b52fb..8e1e81e4 100644 --- a/src/InsaLan/TournamentBundle/Controller/MerchantController.php +++ b/src/InsaLan/TournamentBundle/Controller/MerchantController.php @@ -33,8 +33,9 @@ public function indexAction($id = null) $tournaments = $em->getRepository('InsaLanTournamentBundle:Tournament')->findAll(); $a = array(null => ''); foreach ($tournaments as $t) { - if ($t->isOpenedNow()) + if ($t->isOpenedNow()) { $a[$t->getId()] = $t->getName(); + } } $form = $this->createFormBuilder() @@ -53,9 +54,9 @@ public function indexAction($id = null) $data = $form->getData(); return $this->redirect($this->generateUrl( 'insalan_tournament_merchant_index_1', - array('id' => $data['tournament']))); - } - else if (null !== $id) { + array('id' => $data['tournament']) + )); + } elseif (null !== $id) { $data = array('tournament' => $id); $form->get('tournament')->submit($id); @@ -66,21 +67,24 @@ public function indexAction($id = null) } if (null === $tournament) { - throw new NotFoundHttpException('InsaLan\\TournamentBundle\\Entity\\Tournament object not found.');; + throw new NotFoundHttpException('InsaLan\\TournamentBundle\\Entity\\Tournament object not found.'); + ; } $players = $em->getRepository('InsaLanTournamentBundle:Participant') ->findByTournament($tournament); foreach ($players as &$p) { - if ($p->getParticipantType() == "team"){ + if ($p->getParticipantType() == "team") { foreach ($p->getPlayers() as &$player) { - if (!$player->getPaymentDone()) + if (!$player->getPaymentDone()) { $pendingPlayers[] = $player; + } } - }else{ - if (!$p->getPaymentDone()) + } else { + if (!$p->getPaymentDone()) { $pendingPlayers[] = $p; + } } } @@ -95,9 +99,9 @@ public function indexAction($id = null) $paidParticipant = $em->getRepository('InsaLanTournamentBundle:Participant')->findByUser($order->getPlayer()->getUser()); foreach ($paidParticipant as &$p) { - if ($p->getParticipantType() == "team"){ + if ($p->getParticipantType() == "team") { foreach ($p->getPlayers() as &$player) { - if ($player->getId() == $order->getPlayer()->getId()){ + if ($player->getId() == $order->getPlayer()->getId()) { $order->getPlayer()->setTournament($p->getTournament()); $order->getPlayer()->setValidationDate($p->getValidationDate()); break; @@ -109,8 +113,7 @@ public function indexAction($id = null) if ($order->getPlayer()->getTournament()->isOpenedNow() || $order->getPlayer()->getTournament()->isPending()) { $total += $order->getPayment()["L_PAYMENTREQUEST_0_AMT0"]; $paidPlayers[] = $order; - } - else { + } else { $previousPaidPlayers[] = $order; } } @@ -133,11 +136,12 @@ public function indexAction($id = null) * @Route("/{id}/merchant/{player}/validate", requirements={"id" = "\d+"}) * @Route("/{id}/merchant/{player}/discount/{discount}/validate", requirements={"id" = "\d+"}) */ - public function validateAction(Entity\Tournament $tournament, Entity\Player $player, $discount = null){ + public function validateAction(Entity\Tournament $tournament, Entity\Player $player, $discount = null) + { $em = $this->getDoctrine()->getManager(); $user = $this->get('security.context')->getToken()->getUser(); - if ($player->getUser() == null){ + if ($player->getUser() == null) { $this->get('session')->getFlashBag()->add('error', "Impossible de valider cette place (aucun utilisateur associé à la commande)"); return $this->redirect($this->generateUrl('insalan_tournament_merchant_index_1', array('id' => $tournament->getId()))); } @@ -151,11 +155,11 @@ public function validateAction(Entity\Tournament $tournament, Entity\Player $pla $price = $tournament->getWebPrice(); $title = 'Place pour le tournoi '.$tournament->getName(); - if ($discount !== null){ + if ($discount !== null) { $discount = $em->getRepository('InsaLanUserBundle:Discount') ->findOneById($discount); - if ($discount->getTournament()->getId() !== $tournament->getId()){ + if ($discount->getTournament()->getId() !== $tournament->getId()) { $this->get('session')->getFlashBag()->add('error', "discount not allowed"); return $this->redirect($this->generateUrl('insalan_tournament_merchant_index_1', array('id' => $tournament->getId()))); } @@ -192,6 +196,7 @@ public function validateAction(Entity\Tournament $tournament, Entity\Player $pla return $this->redirect($this->generateUrl( 'insalan_tournament_merchant_index_1', - array('id' => $tournament->getId()))); + array('id' => $tournament->getId()) + )); } } diff --git a/src/InsaLan/TournamentBundle/Controller/UserController.php b/src/InsaLan/TournamentBundle/Controller/UserController.php index 5ba49a1f..dbd3cbd4 100644 --- a/src/InsaLan/TournamentBundle/Controller/UserController.php +++ b/src/InsaLan/TournamentBundle/Controller/UserController.php @@ -42,7 +42,8 @@ class UserController extends Controller * @Route("/user") * @Template() */ - public function indexAction() { + public function indexAction() + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); @@ -59,16 +60,17 @@ public function indexAction() { $participants = $em->getRepository('InsaLanTournamentBundle:Participant')->findByUser($usr); $tournaments = array(); - foreach($rawTournaments as $t) { + foreach ($rawTournaments as $t) { $in = false; - foreach($participants as $p) { - if($p->getTournament()->getId() === $t->getId()) { + foreach ($participants as $p) { + if ($p->getTournament()->getId() === $t->getId()) { $in = true; break; } } - if(!$in) + if (!$in) { $tournaments[] = $t; + } } return array('tournaments' => $tournaments, 'participants' => $participants); @@ -80,11 +82,12 @@ public function indexAction() { * @Route("/{tournament}/user/placement") * @Template() */ - public function placementAction(Request $request, Entity\Tournament $tournament) { + public function placementAction(Request $request, Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); - if(!$tournament->isPending() || !$tournament->getPlacement()) { + if (!$tournament->isPending() || !$tournament->getPlacement()) { $this->get('session')->getFlashBag()->add('error', "Le tournoi ne permet pas de choisir de places actuellement."); return $this->redirect($this->generateUrl('insalan_tournament_user_index')); } @@ -92,7 +95,7 @@ public function placementAction(Request $request, Entity\Tournament $tournament) $participant = $em->getRepository('InsaLanTournamentBundle:Participant') ->findOneByUserAndTournament($usr, $tournament); - if(!$participant || + if (!$participant || $participant->getValidated() !== Entity\Participant::STATUS_VALIDATED || $participant instanceof Entity\Team && $participant->getCaptain()->getUser() !== $usr) { @@ -100,12 +103,12 @@ public function placementAction(Request $request, Entity\Tournament $tournament) return $this->redirect($this->generateUrl('insalan_tournament_user_index')); } - if(null !== ($placement = $request->query->get("placement"))) { + if (null !== ($placement = $request->query->get("placement"))) { $placement = intval($placement); $registered = $em->getRepository('InsaLanTournamentBundle:Participant') ->findOneBy(array("placement" => $placement, "tournament" => $tournament)); - if($registered === null || $registered === $participant) { + if ($registered === null || $registered === $participant) { $participant->setPlacement(intval($placement)); $this->get('session')->getFlashBag()->add('info', "La place vous a bien été attribuée !"); $em->persist($participant); @@ -127,7 +130,8 @@ public function placementAction(Request $request, Entity\Tournament $tournament) * Manage all steps for registering into a tournament * @Route("/{tournament}/user/enroll") */ - public function enrollAction(Request $request, Entity\Tournament $tournament) { + public function enrollAction(Request $request, Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); @@ -139,24 +143,25 @@ public function enrollAction(Request $request, Entity\Tournament $tournament) { if ($player === null && $tournament->isLocked()) { $this->get('session')->getFlashBag()->add('error', "Ce tournois n'est accessible que sur invitation."); return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } elseif ($player === null) { + return $this->redirect($this->generateUrl('insalan_tournament_user_setplayer', array('tournament' => $tournament->getId()))); + } elseif (!$player->getGameValidated()) { + return $this->redirect($this->generateUrl('insalan_tournament_user_validateplayer', array('tournament' => $tournament->getId()))); + } elseif ($tournament->getParticipantType() === 'team' && $player->getTeamForTournament($tournament) === null) { + return $this->redirect($this->generateUrl('insalan_tournament_user_jointeam', array('tournament' => $tournament->getId()))); + } elseif (!$player->getPaymentDone()) { + return $this->redirect($this->generateUrl('insalan_tournament_user_pay', array('tournament' => $tournament->getId()))); + } else { + return $this->redirect($this->generateUrl('insalan_tournament_user_paydone', array('tournament' => $tournament->getId()))); } - else if ($player === null) - return $this->redirect($this->generateUrl('insalan_tournament_user_setplayer',array('tournament' => $tournament->getId()))); - else if (!$player->getGameValidated()) - return $this->redirect($this->generateUrl('insalan_tournament_user_validateplayer',array('tournament' => $tournament->getId()))); - else if ($tournament->getParticipantType() === 'team' && $player->getTeamForTournament($tournament) === null) - return $this->redirect($this->generateUrl('insalan_tournament_user_jointeam',array('tournament' => $tournament->getId()))); - else if (!$player->getPaymentDone()) - return $this->redirect($this->generateUrl('insalan_tournament_user_pay',array('tournament' => $tournament->getId()))); - else - return $this->redirect($this->generateUrl('insalan_tournament_user_paydone',array('tournament' => $tournament->getId()))); } /** * Manage all steps for registering into a LOCKED tournament * @Route("/{tournament}/user/enroll/{authToken}") */ - public function enrollLockedAction(Request $request, Entity\Tournament $tournament, $authToken) { + public function enrollLockedAction(Request $request, Entity\Tournament $tournament, $authToken) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); @@ -170,16 +175,17 @@ public function enrollLockedAction(Request $request, Entity\Tournament $tourname $this->get('session')->getFlashBag()->add('error', "Ce tournois n'est accessible que sur invitation."); return $this->redirect($this->generateUrl('insalan_tournament_user_index')); } // from here we are authentificated - else if ($player === null) - return $this->redirect($this->generateUrl('insalan_tournament_user_setplayer',array('tournament' => $tournament->getId()))); - else if (!$player->getGameValidated()) - return $this->redirect($this->generateUrl('insalan_tournament_user_validateplayer',array('tournament' => $tournament->getId()))); - else if ($tournament->getParticipantType() === 'team' && $player->getTeamForTournament($tournament) === null) - return $this->redirect($this->generateUrl('insalan_tournament_user_jointeam',array('tournament' => $tournament->getId()))); - else if (!$player->getPaymentDone()) - return $this->redirect($this->generateUrl('insalan_tournament_user_pay',array('tournament' => $tournament->getId()))); - else - return $this->redirect($this->generateUrl('insalan_tournament_user_paydone',array('tournament' => $tournament->getId()))); + elseif ($player === null) { + return $this->redirect($this->generateUrl('insalan_tournament_user_setplayer', array('tournament' => $tournament->getId()))); + } elseif (!$player->getGameValidated()) { + return $this->redirect($this->generateUrl('insalan_tournament_user_validateplayer', array('tournament' => $tournament->getId()))); + } elseif ($tournament->getParticipantType() === 'team' && $player->getTeamForTournament($tournament) === null) { + return $this->redirect($this->generateUrl('insalan_tournament_user_jointeam', array('tournament' => $tournament->getId()))); + } elseif (!$player->getPaymentDone()) { + return $this->redirect($this->generateUrl('insalan_tournament_user_pay', array('tournament' => $tournament->getId()))); + } else { + return $this->redirect($this->generateUrl('insalan_tournament_user_paydone', array('tournament' => $tournament->getId()))); + } } /** @@ -187,7 +193,8 @@ public function enrollLockedAction(Request $request, Entity\Tournament $tourname * @Route("/{tournament}/user/player/set") * @Template() */ - public function setPlayerAction(Request $request, Entity\Tournament $tournament) { + public function setPlayerAction(Request $request, Entity\Tournament $tournament) + { $autre = 'other'; $battleNet = 'battlenet'; $steam = 'Steam'; @@ -198,20 +205,22 @@ public function setPlayerAction(Request $request, Entity\Tournament $tournament) $player = $em->getRepository('InsaLanTournamentBundle:Player')->findOneByUserAndPendingTournament($usr, $tournament); $game = $tournament->getType(); $platform = $tournament->getLoginType(); - $this->get('session')->set('callbackRegisterApiRoute','insalan_tournament_user_setplayer'); - $this->get('session')->set('callbackRegisterApiParams',array('tournament' => $tournament->getId())); + $this->get('session')->set('callbackRegisterApiRoute', 'insalan_tournament_user_setplayer'); + $this->get('session')->set('callbackRegisterApiParams', array('tournament' => $tournament->getId())); if ($player === null) { $player = new Player(); $player->setUser($usr); $player->setPendingTournament($tournament); } - if($platform == $autre) { + if ($platform == $autre) { return $this->usernameSet($em, $usr, $player, $request, $tournament); - } else if ($platform == $steam) { - if($usr->getSteamId() == null) { - return $this->redirect($this->generateUrl('insalan_tournament_user_redirecttoapilogin', - array('tournament' => $tournament->getId())).'?api='.$steam); + } elseif ($platform == $steam) { + if ($usr->getSteamId() == null) { + return $this->redirect($this->generateUrl( + 'insalan_tournament_user_redirecttoapilogin', + array('tournament' => $tournament->getId()) + ).'?api='.$steam); } else { $steamKey = $this->getParameter('steam_api_key'); $steamDetails = $usr->getSteamDetails($steamKey); @@ -219,37 +228,42 @@ public function setPlayerAction(Request $request, Entity\Tournament $tournament) $player->setGameName($steamDetails->personaname); $em->persist($player); $em->flush(); - return $this->redirect($this->generateUrl('insalan_tournament_user_validateplayer', - array('tournament' => $tournament->getId()))); + return $this->redirect($this->generateUrl( + 'insalan_tournament_user_validateplayer', + array('tournament' => $tournament->getId()) + )); } - } else if($platform == $battleNet) { - if($usr->getBattleTag() == null) { - - return $this->redirect($this->generateUrl('insalan_tournament_user_redirecttoapilogin', - array('tournament' => $tournament->getId())).'?api='.$battleNet); - + } elseif ($platform == $battleNet) { + if ($usr->getBattleTag() == null) { + return $this->redirect($this->generateUrl( + 'insalan_tournament_user_redirecttoapilogin', + array('tournament' => $tournament->getId()) + ).'?api='.$battleNet); } else { - $name = explode('#',$usr->getBattleTag())[0]; + $name = explode('#', $usr->getBattleTag())[0]; $player->setGameName($name); $em->persist($player); $em->flush(); - return $this->redirect($this->generateUrl('insalan_tournament_user_validateplayer', - array('tournament' => $tournament->getId()))); + return $this->redirect($this->generateUrl( + 'insalan_tournament_user_validateplayer', + array('tournament' => $tournament->getId()) + )); } } } /** - * + * * @Route("/{tournament}/user/player/registerOtherPlatform/") * @Template("InsaLanTournamentBundle:User:redirectToApiLogin.html.twig") */ - public function redirectToApiLoginAction(Request $request, Entity\Tournament $tournament) { + public function redirectToApiLoginAction(Request $request, Entity\Tournament $tournament) + { $link = null; $api = $request->query->get('api'); - if($api == 'Steam') { + if ($api == 'Steam') { $link = $this->generateUrl('insalan_user_default_registersteamid'); - } else if ($api == 'battlenet') { + } elseif ($api == 'battlenet') { $link = $this->generateUrl('insalan_user_default_registerbattlenet'); } return array('api' => $api, 'registerUri' => $link, 'tournament' => $tournament); @@ -258,7 +272,8 @@ public function redirectToApiLoginAction(Request $request, Entity\Tournament $to * Manage validation of player registration into a tournament * @Route("/{tournament}/user/player/validate") */ - public function validatePlayerAction(Request $request, Entity\Tournament $tournament) { + public function validatePlayerAction(Request $request, Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); $player = $em->getRepository('InsaLanTournamentBundle:Player')->findOneByUserAndPendingTournament($usr, $tournament); @@ -266,9 +281,8 @@ public function validatePlayerAction(Request $request, Entity\Tournament $tourna $check = $request->query->get('check') === "yes"; if ($player === null) { - return $this->redirect($this->generateUrl('insalan_tournament_user_setplayer',array('tournament' => $tournament->getId()))); + return $this->redirect($this->generateUrl('insalan_tournament_user_setplayer', array('tournament' => $tournament->getId()))); } else { - $player->setGameValidated(true); $this->finalizePlayerAfterValidation($player, $tournament); $em->persist($player); @@ -283,12 +297,12 @@ public function validatePlayerAction(Request $request, Entity\Tournament $tourna $this->generateUrl('insalan_tournament_user_pay', array('tournament' => $tournament->getId())) ); } - } } - private function finalizePlayerAfterValidation($player, $tournament) { - if($tournament->getParticipantType() === "player") { + private function finalizePlayerAfterValidation($player, $tournament) + { + if ($tournament->getParticipantType() === "player") { $player->setTournament($tournament); } } @@ -297,7 +311,8 @@ private function finalizePlayerAfterValidation($player, $tournament) { * Allow a player to drop a pending tournament registration if not managed by team * @Route("/{tournament}/user/leave") */ - public function leaveAction(Entity\Tournament $tournament) { + public function leaveAction(Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); @@ -305,8 +320,9 @@ public function leaveAction(Entity\Tournament $tournament) { ->getRepository('InsaLanTournamentBundle:Player') ->findOneByUserAndPendingTournament($usr, $tournament); - if($player->getTournament()->getParticipantType() !== "player") + if ($player->getTournament()->getParticipantType() !== "player") { throw new ControllerException("Not Allowed"); // must be a player only tournament + } $em->remove($player); $em->flush(); @@ -320,7 +336,8 @@ public function leaveAction(Entity\Tournament $tournament) { * @Route("/{tournament}/user/discount/{discount}/details", requirements={"discount" = "\d+"}) * @Template() */ - public function payAction(Entity\Tournament $tournament, $discount = null) { + public function payAction(Entity\Tournament $tournament, $discount = null) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); @@ -335,11 +352,11 @@ public function payAction(Entity\Tournament $tournament, $discount = null) { ->getRepository('InsaLanUserBundle:Discount') ->findByTournament($tournament); - if ($discount !== null && $discount->getTournament()->getId() !== $tournament->getId()){ + if ($discount !== null && $discount->getTournament()->getId() !== $tournament->getId()) { return $this->redirect($this->generateUrl('insalan_tournament_user_pay', array("tournament" => $tournament->getId()))); } - if($tournament->isFree()) { + if ($tournament->isFree()) { $player->setPaymentDone(true); $em->persist($player); $em->flush(); @@ -354,7 +371,8 @@ public function payAction(Entity\Tournament $tournament, $discount = null) { * @Route("/{tournament}/user/pay/paypal_ec") * @Route("/{tournament}/user/discount/{discount}/paypal_ec", requirements={"discount" = "\d+"}) */ - public function payPaypalECAction(Entity\Tournament $tournament, $discount = null) { + public function payPaypalECAction(Entity\Tournament $tournament, $discount = null) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); @@ -365,7 +383,7 @@ public function payPaypalECAction(Entity\Tournament $tournament, $discount = nul $discount = $em->getRepository('InsaLanUserBundle:Discount') ->findOneById($discount); - if ($discount !== null && $discount->getTournament()->getId() !== $tournament->getId()){ + if ($discount !== null && $discount->getTournament()->getId() !== $tournament->getId()) { return $this->redirect($this->generateUrl('insalan_tournament_user_pay', array("tournament" => $tournament->getId()))); } @@ -374,7 +392,7 @@ public function payPaypalECAction(Entity\Tournament $tournament, $discount = nul $price = $tournament->getWebPrice(); $title = 'Place pour le tournoi '.$tournament->getName(); - if ($discount !== null){ + if ($discount !== null) { $price -= $discount->getAmount(); $title += " (" + $discount->getName() + ")"; } @@ -419,7 +437,8 @@ public function payPaypalECAction(Entity\Tournament $tournament, $discount = nul * @Route("/{tournament}/user/pay/done") * @Template() */ - public function payDoneAction(Request $request, Entity\Tournament $tournament) { + public function payDoneAction(Request $request, Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); $player = $em @@ -432,7 +451,8 @@ public function payDoneAction(Request $request, Entity\Tournament $tournament) { /** * @Route("/{tournament}/user/pay/done_temp") */ - public function payDoneTempAction(Request $request, Entity\Tournament $tournament) { + public function payDoneTempAction(Request $request, Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); $player = $em @@ -462,7 +482,8 @@ public function payDoneTempAction(Request $request, Entity\Tournament $tournamen * @Route("/{tournament}/user/discount/{discount}/offline", requirements={"discount" = "\d+"}) * @Template() */ - public function payOfflineAction(Request $request, Entity\Tournament $tournament, $discount = null) { + public function payOfflineAction(Request $request, Entity\Tournament $tournament, $discount = null) + { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.context')->getToken()->getUser(); $player = $em @@ -472,7 +493,7 @@ public function payOfflineAction(Request $request, Entity\Tournament $tournament $discount = $em->getRepository('InsaLanUserBundle:Discount') ->findOneById($discount); - if ($discount !== null && $discount->getTournament()->getId() !== $tournament->getId()){ + if ($discount !== null && $discount->getTournament()->getId() !== $tournament->getId()) { return $this->redirect($this->generateUrl('insalan_tournament_user_pay', array("tournament" => $tournament->getId()))); } @@ -499,16 +520,19 @@ public function joinTeamAction(Entity\Tournament $tournament) 'insalan_tournament_user_setplayer', array( 'tournament' => $tournament->getId() - ))); - } - // Check if this player is validated for the game - else if (!$player->isValidated($tournament->getType())) { + ) + ) + ); + } // Check if this player is validated for the game + elseif (!$player->isValidated($tournament->getType())) { return $this->redirect( $this->generateUrl( 'insalan_tournament_user_validateplayer', array( 'tournament' => $tournament->getId() - ))); + ) + ) + ); } return array('tournament' => $tournament, 'user' => $usr, 'player' => $player); @@ -520,14 +544,16 @@ public function joinTeamAction(Entity\Tournament $tournament) * @Route("/user/leave/team/{teamId}") * @Template() */ - public function leaveTeamAction($teamId) { + public function leaveTeamAction($teamId) + { $em = $this->getDoctrine()->getManager(); $team = $em ->getRepository('InsaLanTournamentBundle:Team') ->findOneById($teamId); - if($team === null) + if ($team === null) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } // get targeted player $usr = $this->get('security.context')->getToken()->getUser(); @@ -536,34 +562,39 @@ public function leaveTeamAction($teamId) { ->findOneByUserAndPendingTournament($usr, $team->getTournament()); // is he part of the team roster ? - if(!$team->haveInPlayers($player)) + if (!$team->haveInPlayers($player)) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } // not allowed if he paid something - if(!$team->getTournament()->isFree() && $player->getPaymentDone()){ + if (!$team->getTournament()->isFree() && $player->getPaymentDone()) { $this->get('session')->getFlashBag()->add('error', "Vous avez payé votre place, merci de contacter l'InsaLan si vous souhaitez vous désister."); return $this->redirect($this->generateUrl('insalan_tournament_user_index')); } // not allowed either if registration are closed - if(!$team->getTournament()->isOpenedNow()) + if (!$team->getTournament()->isOpenedNow()) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } $player->leaveTeam($team); $team->removePlayer($player); // if he was captain and not the last member, we need to chose another one - if($team->getCaptain() === $player && $team->getPlayers()->count() === 0) + if ($team->getCaptain() === $player && $team->getPlayers()->count() === 0) { $team->setCaptain($team->getPlayers()->first()); + } // team cannot stay validated if someone leave and there is not enought players // TODO: Should be handled by the model ? - if($team->getPlayers()->count() < $team->getTournament()->getTeamMinPlayer()) + if ($team->getPlayers()->count() < $team->getTournament()->getTeamMinPlayer()) { $team->setValidated(Entity\Participant::STATUS_PENDING); // reset to waiting state + } $em->persist($team); - if($team->getPlayers()->count() === 0) + if ($team->getPlayers()->count() === 0) { $em->remove($team); + } $em->remove($player); $em->flush(); @@ -576,7 +607,8 @@ public function leaveTeamAction($teamId) { * @Template() */ - public function editTeamAction(Request $request, $teamId) { + public function editTeamAction(Request $request, $teamId) + { $em = $this->getDoctrine()->getManager(); $team = $em @@ -584,8 +616,9 @@ public function editTeamAction(Request $request, $teamId) { ->findOneById($teamId); // does the team exist ? - if($team === null) + if ($team === null) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } // get current logged user corresponding player $usr = $this->get('security.context')->getToken()->getUser(); @@ -594,15 +627,16 @@ public function editTeamAction(Request $request, $teamId) { ->findOneByUserAndPendingTournament($usr, $team->getTournament()); // is he really the captain ? (also check for null) - if($team->getCaptain() !== $captain) + if ($team->getCaptain() !== $captain) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } $form = $this->createForm(new TeamType(), $team); $form->handleRequest($request); if ($form->isValid()) { // update password if not empty - if ($team->getPlainPassword() != ""){ + if ($team->getPlainPassword() != "") { $factory = $this->get('security.encoder_factory'); $encoder = $factory->getEncoder($usr); $team->setPassword($encoder->encodePassword($team->getPlainPassword(), $team->getPasswordSalt())); @@ -624,19 +658,22 @@ public function editTeamAction(Request $request, $teamId) { * Only possible if the player didn't pay anything yet OR if this is a free tournament * @Route("/user/ban/team/{teamId}/{playerId}") */ - public function banPlayerAction($teamId, $playerId) { + public function banPlayerAction($teamId, $playerId) + { $em =$this->getDoctrine()->getManager(); $team = $em ->getRepository('InsaLanTournamentBundle:Team') ->findOneById($teamId); // does the team exist ? - if($team === null) + if ($team === null) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } // not allowed if registration are closed - if(!$team->getTournament()->isOpenedNow()) + if (!$team->getTournament()->isOpenedNow()) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } // get current logged user corresponding player $usr = $this->get('security.context')->getToken()->getUser(); @@ -645,20 +682,23 @@ public function banPlayerAction($teamId, $playerId) { ->findOneByUserAndPendingTournament($usr, $team->getTournament()); // is he really the captain ? (also check for null) - if($team->getCaptain() !== $captain) + if ($team->getCaptain() !== $captain) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } $playerToBan = $em ->getRepository('InsaLanTournamentBundle:Player') ->findOneById($playerId); // does this player exist ? - if($playerToBan === null) + if ($playerToBan === null) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } // not possible if the player payed something ! (paid tournament + payement done) - if(!$team->getTournament()->isFree() && $playerToBan->getPaymentDone()) + if (!$team->getTournament()->isFree() && $playerToBan->getPaymentDone()) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } /** * Manage team validation state @@ -666,18 +706,19 @@ public function banPlayerAction($teamId, $playerId) { * - A validated team roster cannot be modified in paid tournaments * - Bans invalidates the team (see below) */ - if(!$team->getTournament()->isFree() && $team->getValidated()) + if (!$team->getTournament()->isFree() && $team->getValidated()) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } // captain cannot ban himself ! - if($playerToBan !== $captain) { - + if ($playerToBan !== $captain) { $playerToBan->leaveTeam($team); $team->removePlayer($playerToBan); - if($team->getValidated() === Entity\Participant::STATUS_WAITING - || $team->getValidated() === Entity\Participant::STATUS_VALIDATED) + if ($team->getValidated() === Entity\Participant::STATUS_WAITING + || $team->getValidated() === Entity\Participant::STATUS_VALIDATED) { $team->setValidated(Entity\Participant::STATUS_PENDING); // reset to waiting state + } $em->persist($team); @@ -692,15 +733,17 @@ public function banPlayerAction($teamId, $playerId) { * Change team captain * @Route("/user/promote/{teamId}/{playerId}") */ - public function promoteCaptainAction($teamId, $playerId){ + public function promoteCaptainAction($teamId, $playerId) + { $em =$this->getDoctrine()->getManager(); $team = $em ->getRepository('InsaLanTournamentBundle:Team') ->findOneById($teamId); // does the team exist ? - if($team === null) + if ($team === null) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } // get current logged user corresponding player $usr = $this->get('security.context')->getToken()->getUser(); @@ -709,20 +752,23 @@ public function promoteCaptainAction($teamId, $playerId){ ->findOneByUserAndPendingTournament($usr, $team->getTournament()); // is he really the captain ? (also check for null) - if($team->getCaptain() !== $captain) + if ($team->getCaptain() !== $captain) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } $playerToPromote = $em ->getRepository('InsaLanTournamentBundle:Player') ->findOneById($playerId); // does this player exist ? - if($playerToPromote === null) + if ($playerToPromote === null) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } // is he part of the team roster ? - if(!$team->haveInPlayers($playerToPromote)) + if (!$team->haveInPlayers($playerToPromote)) { return $this->redirect($this->generateUrl('insalan_tournament_user_index')); + } $team->setCaptain($playerToPromote); $em->persist($team); @@ -736,11 +782,13 @@ public function promoteCaptainAction($teamId, $playerId){ * @Route("{tournament}/user/join/team/create") * @Template() */ - public function createTeamAction(Request $request, Entity\Tournament $tournament) { + public function createTeamAction(Request $request, Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); - if($tournament->getParticipantType() !== "team") + if ($tournament->getParticipantType() !== "team") { throw new ControllerException("Not Allowed"); + } $usr = $this->get('security.context')->getToken()->getUser(); $player = $em @@ -774,11 +822,13 @@ public function createTeamAction(Request $request, Entity\Tournament $tournament * @Route("{tournament}/user/join/team/existing") * @Template() */ - public function existingTeamAction(Request $request, Entity\Tournament $tournament) { + public function existingTeamAction(Request $request, Entity\Tournament $tournament) + { $em = $this->getDoctrine()->getManager(); - if($tournament->getParticipantType() !== "team") + if ($tournament->getParticipantType() !== "team") { throw new ControllerException("Équipes non acceptées dans ce tournois"); + } $usr = $this->get('security.context')->getToken()->getUser(); $player = $em @@ -799,8 +849,9 @@ public function existingTeamAction(Request $request, Entity\Tournament $tourname ->getRepository('InsaLanTournamentBundle:Team') ->findOneByNameAndTournament($team->getName(), $tournament); - if($team2 === null || $team2->getTournament()->getId() !== $tournament->getId()) + if ($team2 === null || $team2->getTournament()->getId() !== $tournament->getId()) { throw new ControllerException("Équipe invalide"); + } $team->setPassword($encoder->encodePassword($team->getPlainPassword(), $team2->getPasswordSalt())); @@ -817,7 +868,6 @@ public function existingTeamAction(Request $request, Entity\Tournament $tourname } catch (ControllerException $e) { $details = $e->getMessage(); } - } return array('tournament' => $tournament, 'user' => $usr, 'player' => $player, 'error' => $details, 'form' => $form->createView()); } @@ -837,14 +887,17 @@ public function teamValidateMatchAction(Entity\Participant $team, Entity\Match $ try { $pvpService = $this->get('insalan.tournament.pvp_net'); - if($match->getPart1() !== $team && $match->getPart2() !== $team) + if ($match->getPart1() !== $team && $match->getPart2() !== $team) { throw new ControllerException("Invalid team"); + } - if(!$this->isUserInTeam($team)) + if (!$this->isUserInTeam($team)) { throw new ControllerException("Invalid user"); + } - if($match->getState() != Entity\Match::STATE_ONGOING) + if ($match->getState() != Entity\Match::STATE_ONGOING) { throw new ControllerException("Invalid match: not in ongoing state"); + } try { $matchResult = $pvpService->getGameResult($match->getPart1(), $match->getPart2()); @@ -853,8 +906,7 @@ public function teamValidateMatchAction(Entity\Participant $team, Entity\Match $ } catch (\Exception $e) { throw new ControllerException($e->getMessage()); } - } - catch (ControllerException $e) { + } catch (ControllerException $e) { $this->get('session')->getFlashBag()->add('error', $e->getMessage()); return $this->redirect($this->generateUrl('insalan_tournament_user_teamdetails', array('id' => $team->getId()))); } @@ -867,10 +919,9 @@ public function teamValidateMatchAction(Entity\Participant $team, Entity\Match $ $round->setData($data); - if($matchResult) { + if ($matchResult) { $round->setScore1(1); - } - else { + } else { $round->setScore2(1); } @@ -884,13 +935,12 @@ public function teamValidateMatchAction(Entity\Participant $team, Entity\Match $ $em->flush(); - if($match->getKoMatch()) { + if ($match->getKoMatch()) { $em->getRepository("InsaLanTournamentBundle:KnockoutMatch")->propagateVictory($match->getKoMatch()); $em->flush(); } return $this->redirect($this->generateUrl('insalan_tournament_user_teamdetails', array('id' => $team->getId()))); - } /** @@ -903,15 +953,18 @@ public function roundAddReplayAction(Request $request, Entity\Participant $team, { try { // Check security - if(!$this->isUserInTeam($team)) + if (!$this->isUserInTeam($team)) { throw new ControllerException("Invalid user"); + } - if($round->getMatch()->getPart1()->getId() !== $team->getId() - && $round->getMatch()->getPart2()->getId() !== $team->getId()) + if ($round->getMatch()->getPart1()->getId() !== $team->getId() + && $round->getMatch()->getPart2()->getId() !== $team->getId()) { throw new ControllerException("Invalid round"); + } - if($round->getReplay() !== null) + if ($round->getReplay() !== null) { throw new ControllerException("Le fichier a déjà été envoyé !"); + } } catch (ControllerException $e) { $this->get('session')->getFlashBag()->add('error', $e->getMessage()); return $this->redirect($this->generateUrl('insalan_tournament_user_teamdetails', array('id' => $team->getId()))); @@ -924,8 +977,7 @@ public function roundAddReplayAction(Request $request, Entity\Participant $team, $form->handleRequest($request); - if ($form->isValid()) - { + if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($round); $em->flush(); @@ -938,7 +990,8 @@ public function roundAddReplayAction(Request $request, Entity\Participant $team, /** PRIVATE **/ - protected function usernameSet($em, $usr, $player, $request, $tournament) { + protected function usernameSet($em, $usr, $player, $request, $tournament) + { $form = $this->createForm(new SetPlayerName(), $player); $form->handleRequest($request); @@ -955,15 +1008,18 @@ protected function usernameSet($em, $usr, $player, $request, $tournament) { return array('form' => $form->createView(), 'selectedGame' => $tournament->getType(), 'tournamentId' => $tournament->getId()); } - protected function lolValidation($em, $usr, $player, $tournamentId, $check) { + protected function lolValidation($em, $usr, $player, $tournamentId, $check) + { if ($player->getGameValidated()) { return $this->redirect( $this->generateUrl( 'insalan_tournament_user_jointeam', array( 'id' => $tournamentId - ))); - } else if (!$check) { + ) + ) + ); + } elseif (!$check) { return array('player' => $player, 'error' => null, 'selectedGame' => 'lol', 'tournamentId' => $tournamentId); } else { $details = null; @@ -971,13 +1027,12 @@ protected function lolValidation($em, $usr, $player, $tournamentId, $check) { $this->fetchInfo($usr, $player); $em->persist($player); $em->flush(); - } catch(\Exception $e) { + } catch (\Exception $e) { $className = get_class($e); if ('GuzzleHttp\\Exception\\ClientException' === $className && 404 == $e->getResponse()->getStatusCode()) { $details = 'Invocateur introuvable sur EUW'; - } - else if (0 === strpos($className, 'GuzzleHttp')) { + } elseif (0 === strpos($className, 'GuzzleHttp')) { $details = 'Erreur de l\'API. Veuillez réessayer.'; } else { $details = 'Une erreur inconnue est survenue'; @@ -985,24 +1040,23 @@ protected function lolValidation($em, $usr, $player, $tournamentId, $check) { } return array('player' => $player, 'error' => $details, 'selectedGame' => 'lol', 'tournamentId' => $tournamentId); } - } - private function isUserInTeam(Entity\Participant $part) { + private function isUserInTeam(Entity\Participant $part) + { $user = $this->get('security.context')->getToken()->getUser(); - if($part instanceof Entity\Team) { - + if ($part instanceof Entity\Team) { foreach ($part->getPlayers() as $p) { - if($p->getUser() !== null && $p->getUser()->getId() === $user->getId()) + if ($p->getUser() !== null && $p->getUser()->getId() === $user->getId()) { return true; + } } return false; } return $part->getUser() === $user && $user !== null; - } /** @@ -1010,7 +1064,8 @@ private function isUserInTeam(Entity\Participant $part) { * @param User $user targeted user * @param Player $player player associated with user for the tournament to check */ - protected function fetchInfo($user, $player) { + protected function fetchInfo($user, $player) + { $apiLol = $this->container->get('insalan.lol'); $apiSummoner = $apiLol->getApi()->summoner(); $rSummoner = $apiSummoner->info($player->getGameName()); diff --git a/src/InsaLan/TournamentBundle/DataFixtures/ORM/RoundLoader.php b/src/InsaLan/TournamentBundle/DataFixtures/ORM/RoundLoader.php index ca6c038e..e33bd7c6 100644 --- a/src/InsaLan/TournamentBundle/DataFixtures/ORM/RoundLoader.php +++ b/src/InsaLan/TournamentBundle/DataFixtures/ORM/RoundLoader.php @@ -16,8 +16,7 @@ public function getOrder() public function load(ObjectManager $manager) { - for($i = 1; $i < 4; $i++) - { + for ($i = 1; $i < 4; $i++) { $e = new Round(); $e->setMatch($this->getReference('match-'.$i)); $e->setScore1(mt_rand(0, 1)); diff --git a/src/InsaLan/TournamentBundle/DataFixtures/ORM/TeamLoader.php b/src/InsaLan/TournamentBundle/DataFixtures/ORM/TeamLoader.php index 1a2f258b..c3d2bc9f 100644 --- a/src/InsaLan/TournamentBundle/DataFixtures/ORM/TeamLoader.php +++ b/src/InsaLan/TournamentBundle/DataFixtures/ORM/TeamLoader.php @@ -18,7 +18,7 @@ class TeamLoader extends AbstractFixture implements OrderedFixtureInterface, Con /** * {@inheritDoc} - */ + */ public function setContainer(ContainerInterface $container = null) { $this->container = $container; diff --git a/src/InsaLan/TournamentBundle/DataFixtures/ORM/TournamentLoader.php b/src/InsaLan/TournamentBundle/DataFixtures/ORM/TournamentLoader.php index 6fdc271b..20d9ff5b 100644 --- a/src/InsaLan/TournamentBundle/DataFixtures/ORM/TournamentLoader.php +++ b/src/InsaLan/TournamentBundle/DataFixtures/ORM/TournamentLoader.php @@ -33,7 +33,7 @@ public function load(ObjectManager $manager) $e->setType('manual'); $e->setLogoPath('fixtures-1.png'); $e->setParticipantType('player'); - $e->setLoginType('Steam'); + $e->setLoginType('Steam'); $manager->persist($e); $this->addReference('tournament-1', $e); @@ -55,7 +55,7 @@ public function load(ObjectManager $manager) $e->setType('lol'); $e->setLogoPath('fixtures-2.png'); $e->setParticipantType('team'); - $e->setLoginType('Autre'); + $e->setLoginType('Autre'); $manager->persist($e); $this->addReference('tournament-2', $e); @@ -78,7 +78,7 @@ public function load(ObjectManager $manager) $e->setType('manual'); $e->setLogoPath('fixtures-3.png'); $e->setParticipantType('player'); - $e->setLoginType('BattleNet'); + $e->setLoginType('BattleNet'); $manager->persist($e); $this->addReference('tournament-3', $e); @@ -100,7 +100,7 @@ public function load(ObjectManager $manager) $e->setType('manual'); $e->setLogoPath('fixtures-4.png'); $e->setParticipantType('team'); - $e->setLoginType('Steam'); + $e->setLoginType('Steam'); $manager->persist($e); $this->addReference('tournament-4', $e); diff --git a/src/InsaLan/TournamentBundle/Entity/Group.php b/src/InsaLan/TournamentBundle/Entity/Group.php index d160e763..ed9d2e39 100644 --- a/src/InsaLan/TournamentBundle/Entity/Group.php +++ b/src/InsaLan/TournamentBundle/Entity/Group.php @@ -152,12 +152,10 @@ public function countWins() if ($score1 < $score2) { ++$p1['lost']; ++$p2['won']; - } - else if ($score1 > $score2) { + } elseif ($score1 > $score2) { ++$p1['won']; ++$p2['lost']; - } - else { + } else { ++$p1['draw']; ++$p2['draw']; } @@ -190,8 +188,10 @@ public function getStage() } public function __toString() - { - if($this->getStage() === null) return ""; + { + if ($this->getStage() === null) { + return ""; + } return $this->getName() . " " . $this->getStage()->__toString(); } @@ -216,7 +216,6 @@ public function addParticipant(\InsaLan\TournamentBundle\Entity\Participant $par public function removeParticipant(\InsaLan\TournamentBundle\Entity\Participant $participants) { return $this->participants->removeElement($participants); - } /** @@ -245,11 +244,11 @@ public function getMatchBetween(\InsaLan\TournamentBundle\Entity\Participant $A, { $matches = $this->getMatches()->toArray(); - foreach($matches as $match) - { - if(($match->getPart1() === $A && $match->getPart2() === $B) || - ($match->getPart1() === $B && $match->getPart2() === $A)) + foreach ($matches as $match) { + if (($match->getPart1() === $A && $match->getPart2() === $B) || + ($match->getPart1() === $B && $match->getPart2() === $A)) { return $match; + } } return null; diff --git a/src/InsaLan/TournamentBundle/Entity/GroupRepository.php b/src/InsaLan/TournamentBundle/Entity/GroupRepository.php index 86373488..31ba0beb 100644 --- a/src/InsaLan/TournamentBundle/Entity/GroupRepository.php +++ b/src/InsaLan/TournamentBundle/Entity/GroupRepository.php @@ -23,7 +23,7 @@ protected function getQueryBuilder($gs = true) ->addSelect('p2'); if ($gs) { - $qb + $qb ->leftJoin('g.stage', 'gs') ->addSelect('partial gs.{id, name}') ->orderBy('gs.name, g.name'); @@ -32,7 +32,7 @@ protected function getQueryBuilder($gs = true) return $qb; } - public function getByStages(Array $stages) + public function getByStages(array $stages) { $q = $this->getQueryBuilder(); $s = array(); diff --git a/src/InsaLan/TournamentBundle/Entity/GroupStage.php b/src/InsaLan/TournamentBundle/Entity/GroupStage.php index 62171342..d25828c7 100644 --- a/src/InsaLan/TournamentBundle/Entity/GroupStage.php +++ b/src/InsaLan/TournamentBundle/Entity/GroupStage.php @@ -131,8 +131,11 @@ public function getGroups() } public function __toString() - { - if(!$this->getTournament()) return ''; - else return $this->getName() . ' ' . $this->getTournament()->__toString() ; + { + if (!$this->getTournament()) { + return ''; + } else { + return $this->getName() . ' ' . $this->getTournament()->__toString() ; + } } } diff --git a/src/InsaLan/TournamentBundle/Entity/Knockout.php b/src/InsaLan/TournamentBundle/Entity/Knockout.php index d62880e9..28c6eb65 100644 --- a/src/InsaLan/TournamentBundle/Entity/Knockout.php +++ b/src/InsaLan/TournamentBundle/Entity/Knockout.php @@ -41,10 +41,12 @@ class Knockout /** For Bracket Generation **/ protected $size; - public function getSize() { + public function getSize() + { return $this->size; } - public function setSize($s) { + public function setSize($s) + { $this->size = intval($s); } @@ -58,12 +60,12 @@ public function __construct() } public function __toString() - { - if($this->tournament) + { + if ($this->tournament) { return $this->name . " " . $this->tournament->getName(); - - else + } else { return $this->name; + } } /** @@ -138,7 +140,7 @@ public function setDoubleElimination($doubleElimination) /** * Get doubleElimination * - * @return boolean + * @return boolean */ public function getDoubleElimination() { diff --git a/src/InsaLan/TournamentBundle/Entity/KnockoutMatch.php b/src/InsaLan/TournamentBundle/Entity/KnockoutMatch.php index bcd7a112..712dc4d2 100644 --- a/src/InsaLan/TournamentBundle/Entity/KnockoutMatch.php +++ b/src/InsaLan/TournamentBundle/Entity/KnockoutMatch.php @@ -2,7 +2,7 @@ /** * Uses Tree extension for Doctrine (Nested Set) - * + * * https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/tree.md */ @@ -81,7 +81,7 @@ class KnockoutMatch /** - * @ORM\Column(type="boolean") + * @ORM\Column(type="boolean") */ private $oddNode; // if true, this node is waiting for a player from winner bracket @@ -103,36 +103,54 @@ public function __construct() * @return String A french description of this match level in the tree */ public function getFrenchLevel() - { - if(!$this->getKnockout()->getDoubleElimination()) { + { + if (!$this->getKnockout()->getDoubleElimination()) { switch ($this->getLevel()) { - case 0: return "Finale"; - case 1: return "Demi-finale"; - case 2: return "1/4 de finale"; - case 3: return "1/8 de finale"; - case 4: return "1/16 de finale"; - case 5: return "1/32 de finale"; - case 6: return "1/64 de finale"; - default: return "?"; + case 0: + return "Finale"; + case 1: + return "Demi-finale"; + case 2: + return "1/4 de finale"; + case 3: + return "1/8 de finale"; + case 4: + return "1/16 de finale"; + case 5: + return "1/32 de finale"; + case 6: + return "1/64 de finale"; + default: + return "?"; } } else { - if($this->getLevel() === 0) return "GRANDE FINALE"; + if ($this->getLevel() === 0) { + return "GRANDE FINALE"; + } $p = "W.B."; - if(!$this->getLoserDestination()) + if (!$this->getLoserDestination()) { $p = "L.B."; + } switch ($this->getLevel()) { - case 1: return "Finale " . $p; - case 2: return "Demi-finale " . $p; - case 3: return "1/4 de finale " . $p; - case 4: return "1/8 de finale " . $p; - case 5: return "1/16 de finale " . $p; - case 6: return "1/32 de finale " . $p; - case 7: return "1/64 de finale " . $p; - default: return "?"; + case 1: + return "Finale " . $p; + case 2: + return "Demi-finale " . $p; + case 3: + return "1/4 de finale " . $p; + case 4: + return "1/8 de finale " . $p; + case 5: + return "1/16 de finale " . $p; + case 6: + return "1/32 de finale " . $p; + case 7: + return "1/64 de finale " . $p; + default: + return "?"; } } - } public function __toString() @@ -383,7 +401,7 @@ public function setLoserDestination(\InsaLan\TournamentBundle\Entity\KnockoutMat /** * Get loserDestination * - * @return \InsaLan\TournamentBundle\Entity\KnockoutMatch + * @return \InsaLan\TournamentBundle\Entity\KnockoutMatch */ public function getLoserDestination() { @@ -406,11 +424,10 @@ public function setOddNode($oddNode) /** * Get oddNode * - * @return boolean + * @return boolean */ public function getOddNode() { return $this->oddNode; } - } diff --git a/src/InsaLan/TournamentBundle/Entity/KnockoutMatchRepository.php b/src/InsaLan/TournamentBundle/Entity/KnockoutMatchRepository.php index 4dc83563..25fb1b3e 100644 --- a/src/InsaLan/TournamentBundle/Entity/KnockoutMatchRepository.php +++ b/src/InsaLan/TournamentBundle/Entity/KnockoutMatchRepository.php @@ -15,7 +15,8 @@ use Gedmo\Tree\Entity\Repository\NestedTreeRepository; class KnockoutMatchRepository extends NestedTreeRepository -{ +{ + /** * Generate a correct sized tree based on players number. @@ -24,13 +25,17 @@ class KnockoutMatchRepository extends NestedTreeRepository * @param Boolean $doubleElimination * @return KnockoutMatch The root of the tree */ - public function generateMatches(Knockout $knockout, $players, $doubleElimination = false) { + public function generateMatches(Knockout $knockout, $players, $doubleElimination = false) + { $players = intval($players); - if($players <= 1) + if ($players <= 1) { throw new \Exception("Wrong number of players while generating a KO tree"); + } $lvl = 1; - while(pow(2, $lvl) < $players) { $lvl++; } + while (pow(2, $lvl) < $players) { + $lvl++; + } $em = $this->getEntityManager(); @@ -39,8 +44,7 @@ public function generateMatches(Knockout $knockout, $players, $doubleElimination $this->createChildren($root, $lvl - 1); - if($doubleElimination) { - + if ($doubleElimination) { $winnerRoot = $root; $knockout->setDoubleElimination(true); $loserRoot = new KnockoutMatch(); @@ -69,15 +73,14 @@ public function generateMatches(Knockout $knockout, $players, $doubleElimination $order = "asc"; $this->linkMatches($winnerRoot, $loserRoot, $i, $j, $order, true); - $i--; $j--; - - while($i > 0) { + $i--; + $j--; + while ($i > 0) { $order = ($order === "asc" ? "desc" : "asc"); $this->linkMatches($winnerRoot, $loserRoot, $i, $j, $order); $i--; $j-=2; - } $root = $globalRoot; @@ -93,26 +96,28 @@ public function generateMatches(Knockout $knockout, $players, $doubleElimination /** * Propagate each knockoutMatch in a Knockout * It handles correctly null participants and absent matches - * + * * @param Knockout $ko */ - public function propagateVictoryAll(Knockout $ko) { + public function propagateVictoryAll(Knockout $ko) + { $globalRoot = $this->getRoot($ko); $this->propagateFromNode($globalRoot); } /** * Propagate a knockoutMatch and its children - * + * * @param KnockoutMatch $koMatch */ - public function propagateFromNode(KnockoutMatch $koMatch) { + public function propagateFromNode(KnockoutMatch $koMatch) + { $children = $koMatch->getChildren()->toArray(); $allChildrenEnded = true; - foreach($children as $child) { + foreach ($children as $child) { $this->propagateFromNode($child); $allChildrenEnded &= $child->getMatch() !== null && $child->getMatch()->getState() === Match::STATE_FINISHED; @@ -120,15 +125,14 @@ public function propagateFromNode(KnockoutMatch $koMatch) { //echo("Propagating " . $koMatch->__toString() . " : "); - if($allChildrenEnded && // if children are ok + if ($allChildrenEnded && // if children are ok (!$koMatch->getOddNode() || $koMatch->cancelWait || // we are not waiting for somebody in winner bracket (sizeof($koMatch->getChildren()) > 0 && $koMatch->getMatch() && $koMatch->getMatch()->getPart2()))) { - //echo " (candidate) "; // All children are propagated and we are not waiting for another team. // Let's check if this is not an empty match - if(!($match = $koMatch->getMatch())) { + if (!($match = $koMatch->getMatch())) { $match = new Match(); $match->setKoMatch($koMatch); $koMatch->setMatch($match); @@ -136,12 +140,11 @@ public function propagateFromNode(KnockoutMatch $koMatch) { //echo $match->getState() . " "; - if($match->getState() !== Match::STATE_FINISHED) { - if(!$match->getPart2()) { + if ($match->getState() !== Match::STATE_FINISHED) { + if (!$match->getPart2()) { $this->setVictoryForPart1($match); //echo("Victory is for part2"); - } - elseif(!$match->getPart1()) { + } elseif (!$match->getPart1()) { $this->setVictoryForPart2($match); //echo("Victory is for part1"); } @@ -149,12 +152,11 @@ public function propagateFromNode(KnockoutMatch $koMatch) { } $loserKo = $koMatch->getLoserDestination(); - if($loserKo && (!$match->getPart1() || !$match->getPart2())) { + if ($loserKo && (!$match->getPart1() || !$match->getPart2())) { $loserKo->cancelWait = true; $loserKo->setOddNode(false); $this->getEntityManager()->persist($loserKo); } - } //echo("\n"); @@ -165,10 +167,11 @@ public function propagateFromNode(KnockoutMatch $koMatch) { /** * Propagate winner into the tree to the immediate parent * and to the associated loser bracket match - * + * * @param KnockoutMatch $koMatch */ - public function propagateVictory(KnockoutMatch $koMatch) { + public function propagateVictory(KnockoutMatch $koMatch) + { $em = $this->getEntityManager(); $match = $koMatch->getMatch(); $parent = $koMatch->getParent(); @@ -178,61 +181,69 @@ public function propagateVictory(KnockoutMatch $koMatch) { $children = $this->getChildren($parent, true, 'left'); - foreach($children as $i=>$child) { - if($i === 0 && $child !== $koMatch) + foreach ($children as $i => $child) { + if ($i === 0 && $child !== $koMatch) { $first = false; + } } - if($match === null || $match->getState() !== Match::STATE_FINISHED || $parent === null) + if ($match === null || $match->getState() !== Match::STATE_FINISHED || $parent === null) { return; + } $winner = $match->getWinner(); $parentMatch = $parent->getMatch(); - if($parentMatch === null) { + if ($parentMatch === null) { $parentMatch = new Match(); $parentMatch->setKoMatch($parent); $parent->setMatch($parentMatch); } - if($first) + if ($first) { $parentMatch->setPart1($winner); - else + } else { $parentMatch->setPart2($winner); + } $em->persist($parentMatch); $em->persist($parent); - /** + /** * Loser management if needed */ - if(!$koMatch->getKnockout()->getDoubleElimination()) return; + if (!$koMatch->getKnockout()->getDoubleElimination()) { + return; + } $loser = $match->getLoser(); $loserKo = $koMatch->getLoserDestination(); - if(!$loserKo) return; + if (!$loserKo) { + return; + } $loserMatch = $loserKo->getMatch(); - if(!$loserMatch) { + if (!$loserMatch) { $loserMatch = new Match(); $loserMatch->setKoMatch($loserKo); $loserKo->setMatch($loserMatch); } - if($loserKo->getChildren()->isEmpty()) { - if($first) + if ($loserKo->getChildren()->isEmpty()) { + if ($first) { $loserMatch->setPart1($loser); - else + } else { $loserMatch->setPart2($loser); - } else + } + } else { $loserMatch->setPart2($loser); + } $em->persist($loserMatch); $em->persist($loserKo); - } /** @@ -240,7 +251,8 @@ public function propagateVictory(KnockoutMatch $koMatch) { * @param Knockout $ko The knockout container * @return KnockoutMatch */ - public function getRoot(Knockout $ko) { + public function getRoot(Knockout $ko) + { $q = $this->createQueryBuilder('kom') ->where('kom.knockout = :k AND kom.parent IS NULL') ->setParameter('k', $ko); @@ -253,17 +265,18 @@ public function getRoot(Knockout $ko) { * For example : * * X - * X X + * X X * X * X X - * X + * X * * Has a depth of 2 * * @param Knockout $ko [description] * @return [type] [description] */ - public function getDepth(Knockout $ko) { + public function getDepth(Knockout $ko) + { $q = $this->createQueryBuilder('kom') ->select('MAX(kom.level)') ->where('kom.knockout = :k') @@ -272,10 +285,11 @@ public function getDepth(Knockout $ko) { return intval($q->getQuery()->getSingleScalarResult()); } - public function getLeftDepth(Knockout $ko) { + public function getLeftDepth(Knockout $ko) + { $element = $this->getRoot($ko); $children = $element->getChildren(); - while(!$children->isEmpty()) { + while (!$children->isEmpty()) { $element = $children->get(0); $children = $element->getChildren(); } @@ -286,20 +300,23 @@ public function getLeftDepth(Knockout $ko) { /** * Get children that are at a specific level, sorted from left to right * @param Knockout $ko The knockout tree - * @param Number $lvl + * @param Number $lvl * @return KnockoutMatch[] */ - public function getLvlChildren(KnockoutMatch $root, $lvl, $sortOrder = "asc") { + public function getLvlChildren(KnockoutMatch $root, $lvl, $sortOrder = "asc") + { - if($root->getLevel() === $lvl) return array($root); + if ($root->getLevel() === $lvl) { + return array($root); + } $children = $this->getChildren($root, null, "left", $sortOrder); $outChildren = array(); - foreach($children as $child) - { - if($child->getLevel() === $lvl) + foreach ($children as $child) { + if ($child->getLevel() === $lvl) { $outChildren[] = $child; + } } return $outChildren; @@ -310,7 +327,8 @@ public function getLvlChildren(KnockoutMatch $root, $lvl, $sortOrder = "asc") { * @param Knockout $ko * @return String */ - public function getJson(Knockout $ko) { + public function getJson(Knockout $ko) + { $teams = array(); $depth = $this->getLeftDepth($ko); @@ -319,10 +337,9 @@ public function getJson(Knockout $ko) { $root = $ko->getDoubleElimination() ? $globalRoot->getChildren()->get(0) : $globalRoot; $children = $this->getLvlChildren($root, $depth); - foreach($children as $child) { - + foreach ($children as $child) { $match = $child->getMatch(); - if($match === null) { + if ($match === null) { $teams[] = array("-", "-"); continue; } @@ -330,53 +347,59 @@ public function getJson(Knockout $ko) { $part1 = $match->getPart1(); $part2 = $match->getPart2(); - if($part1 === null) $part1 = "-"; - else $part1 = $part1->getName(); + if ($part1 === null) { + $part1 = "-"; + } else { + $part1 = $part1->getName(); + } - if($part2 === null) $part2 = "-"; - else $part2 = $part2->getName(); + if ($part2 === null) { + $part2 = "-"; + } else { + $part2 = $part2->getName(); + } $teams[] = array($part1, $part2); } $results = array(); - for($lvl = $depth; $lvl >= ($ko->getDoubleElimination() ? 1 : 0); $lvl--) { + for ($lvl = $depth; $lvl >= ($ko->getDoubleElimination() ? 1 : 0); $lvl--) { $parents = array(); $round = array(); $i = 0; - foreach($children as $child) { - - if($i++ % 2 === 0) + foreach ($children as $child) { + if ($i++ % 2 === 0) { $parents[] = $child->getParent(); + } $round[] = $this->getMatchJson($child); - } $results[] = $round; $children = $parents; } - if(!$ko->getDoubleElimination()) - + if (!$ko->getDoubleElimination()) { return json_encode(array( "teams" => $teams, "results" => $results )); + } $losers = array(); $root = $globalRoot->getChildren()->get(1); $depth = $this->getDepth($ko); $children = $this->getLvlChildren($root, $depth); - for($lvl = $depth; $lvl >= 1; $lvl--) { + for ($lvl = $depth; $lvl >= 1; $lvl--) { $parents = array(); $round = array(); $i = 0; - foreach($children as $child) { + foreach ($children as $child) { $parent = $child->getParent(); - if($parent && !in_array($parent, $parents)) + if ($parent && !in_array($parent, $parents)) { $parents[] = $parent; + } $round[] = $this->getMatchJson($child); } $losers[] = $round; @@ -389,51 +412,57 @@ public function getJson(Knockout $ko) { "teams" => $teams, "results" => array($results, $losers, array($finals)) )); - } /***** PRIVATE ******/ - private function getMatchJson($child) { + private function getMatchJson($child) + { $match = $child->getMatch(); - if($match === null) { + if ($match === null) { return array(null, null); } return array($match->getScore1(), $match->getScore2()); } - private function createChildren(KnockoutMatch $koMatch, $depth) { - if($depth <= 0) return; + private function createChildren(KnockoutMatch $koMatch, $depth) + { + if ($depth <= 0) { + return; + } - for($i = 0; $i < 2; $i++) { + for ($i = 0; $i < 2; $i++) { $child = $this->addChild($koMatch); $this->createChildren($child, $depth - 1); $this->getEntityManager()->persist($child); } - } - private function createLoserChildren(KnockoutMatch $koMatch, $depth, $importLoser) { - if($depth <= 0) { + private function createLoserChildren(KnockoutMatch $koMatch, $depth, $importLoser) + { + if ($depth <= 0) { $koMatch->setOddNode(true); return; } - for($i = 0; $i < ($importLoser ? 1 : 2); $i++) { + for ($i = 0; $i < ($importLoser ? 1 : 2); $i++) { $child = $this->addChild($koMatch); $this->createLoserChildren($child, $depth - 1, !$importLoser); $this->getEntityManager()->persist($child); } - if($importLoser) + if ($importLoser) { $koMatch->setOddNode(true); + } } - private function addChild(KnockoutMatch $parent, KnockoutMatch $child = null) { - if(!$child) + private function addChild(KnockoutMatch $parent, KnockoutMatch $child = null) + { + if (!$child) { $child = new KnockoutMatch(); + } $child->setKnockout($parent->getKnockout()); $child->setParent($parent); @@ -442,22 +471,23 @@ private function addChild(KnockoutMatch $parent, KnockoutMatch $child = null) { return $child; } - private function linkMatches($winRoot, $losRoot, $winLvl, $losLvl, $order, $first = false) { + private function linkMatches($winRoot, $losRoot, $winLvl, $losLvl, $order, $first = false) + { $winMatches = $this->getLvlChildren($winRoot, $winLvl, $order); $losMatches = $this->getLvlChildren($losRoot, $losLvl, "asc"); $i = 0; - foreach($losMatches as $losMatch) { - for($j = 0; $j < ($first ? 2 : 1); $j++) { + foreach ($losMatches as $losMatch) { + for ($j = 0; $j < ($first ? 2 : 1); $j++) { $winMatches[$i]->setLoserDestination($losMatch); $this->getEntityManager()->persist($winMatches[$i++]); } } - } - private function setVictoryForPart1(Match $match) { + private function setVictoryForPart1(Match $match) + { $r = new Round(); $r->setScore1(1); $r->setScore2(0); @@ -468,7 +498,8 @@ private function setVictoryForPart1(Match $match) { $this->getEntityManager()->persist($match); } - private function setVictoryForPart2(Match $match) { + private function setVictoryForPart2(Match $match) + { $r = new Round(); $r->setScore1(0); $r->setScore2(1); @@ -478,5 +509,4 @@ private function setVictoryForPart2(Match $match) { $this->getEntityManager()->persist($r); $this->getEntityManager()->persist($match); } - -} \ No newline at end of file +} diff --git a/src/InsaLan/TournamentBundle/Entity/Manager.php b/src/InsaLan/TournamentBundle/Entity/Manager.php index 2296f466..1a75b751 100644 --- a/src/InsaLan/TournamentBundle/Entity/Manager.php +++ b/src/InsaLan/TournamentBundle/Entity/Manager.php @@ -62,7 +62,8 @@ class Manager */ protected $arrived; - public function getParticipantType() { + public function getParticipantType() + { return "manager"; } @@ -197,7 +198,8 @@ public function setPaymentDone($paymentDone) return $this; } - public function isOk() { + public function isOk() + { return $this->paymentDone; } @@ -229,14 +231,16 @@ public function getArrived() * * @return String */ - public function __toString() { + public function __toString() + { return $this->getName(); } /** * is set */ - public function isNamed($type) { + public function isNamed($type) + { return $this->gameName !== null; } @@ -245,7 +249,8 @@ public function isNamed($type) { * * @return string */ - public function getName() { + public function getName() + { if (isset($this->gameName)) { return $this->gameName; } else { diff --git a/src/InsaLan/TournamentBundle/Entity/ManagerRepository.php b/src/InsaLan/TournamentBundle/Entity/ManagerRepository.php index abdcd6c2..b7ae19d0 100644 --- a/src/InsaLan/TournamentBundle/Entity/ManagerRepository.php +++ b/src/InsaLan/TournamentBundle/Entity/ManagerRepository.php @@ -6,7 +6,8 @@ class ManagerRepository extends EntityRepository { - public function findOneByUserAndPendingTournament(\InsaLan\UserBundle\Entity\User $u, Tournament $t) { + public function findOneByUserAndPendingTournament(\InsaLan\UserBundle\Entity\User $u, Tournament $t) + { $q = $this->createQueryBuilder('m') ->where('m.user = :user AND m.tournament = :tournament') @@ -15,7 +16,7 @@ public function findOneByUserAndPendingTournament(\InsaLan\UserBundle\Entity\Use try { return $q->getQuery()->getSingleResult(); - } catch(\Exception $e) { + } catch (\Exception $e) { return null; } } diff --git a/src/InsaLan/TournamentBundle/Entity/Match.php b/src/InsaLan/TournamentBundle/Entity/Match.php index 06f58596..97e1b8e6 100644 --- a/src/InsaLan/TournamentBundle/Entity/Match.php +++ b/src/InsaLan/TournamentBundle/Entity/Match.php @@ -61,70 +61,73 @@ public function __toString() } public function getTournament() - { - if($this->getGroup()) + { + if ($this->getGroup()) { return $this->getGroup()->getTournament(); - elseif($this->getKoMatch()) + } elseif ($this->getKoMatch()) { return $this->getKoMatch()->getKnockout()->getTournament(); - else + } else { return null; + } } public function getGroupStage() - { - if($this->getGroup()) + { + if ($this->getGroup()) { return $this->getGroup()->getStage(); - else + } else { return null; + } } public function getExtraInfos() - { + { - if($this->getGroup()) - { + if ($this->getGroup()) { return $this->getGroup()->__toString(); - } - - elseif($this->getKoMatch()) - { + } elseif ($this->getKoMatch()) { return $this->getKoMatch()->__toString(); + } else { + return "?"; } - - else return "?"; - } + } public function getWinner() - { + { - if($this->getPart1() === null && $this->getPart2() !== null) + if ($this->getPart1() === null && $this->getPart2() !== null) { return $this->getPart2(); + } - if($this->getPart2() === null && $this->getPart1() !== null) + if ($this->getPart2() === null && $this->getPart1() !== null) { return $this->getPart1(); + } $won1 = $this->getScore1(); $won2 = $this->getScore2(); - if($won1 === $won2) return null; + if ($won1 === $won2) { + return null; + } return ($won1 > $won2 ? $this->getPart1() : $this->getPart2()); } public function getLoser() { $winner = $this->getWinner(); - if(!$winner) return null; + if (!$winner) { + return null; + } return ($this->getPart1() === $winner ? $this->getPart2() : $this->getPart1()); - } public function getScore1() - { + { $won = 0; - foreach($this->getRounds() as $r) - { - if($r->getScore1() > $r->getScore2()) + foreach ($this->getRounds() as $r) { + if ($r->getScore1() > $r->getScore2()) { $won++; + } } return $won; } @@ -132,10 +135,10 @@ public function getScore1() public function getScore2() { $won = 0; - foreach($this->getRounds() as $r) - { - if($r->getScore2() > $r->getScore1()) + foreach ($this->getRounds() as $r) { + if ($r->getScore2() > $r->getScore1()) { $won++; + } } return $won; } diff --git a/src/InsaLan/TournamentBundle/Entity/Participant.php b/src/InsaLan/TournamentBundle/Entity/Participant.php index db2f9884..3ed63a16 100644 --- a/src/InsaLan/TournamentBundle/Entity/Participant.php +++ b/src/InsaLan/TournamentBundle/Entity/Participant.php @@ -55,7 +55,8 @@ abstract class Participant */ protected $manager; - public function getParticipantType() { + public function getParticipantType() + { return "participant"; } @@ -76,7 +77,7 @@ public function __construct() $this->groups = new \Doctrine\Common\Collections\ArrayCollection(); } - public abstract function getName(); + abstract public function getName(); /** * Set tournament @@ -149,8 +150,9 @@ public function setValidated($validated) { $this->validated = $validated; - if($validated === $this::STATUS_VALIDATED) + if ($validated === $this::STATUS_VALIDATED) { $this->setValidationDate(new \DateTime("now")); + } return $this; } @@ -187,7 +189,7 @@ public function setPlacement($placement) /** * Get placement * - * @return integer + * @return integer */ public function getPlacement() { @@ -209,7 +211,7 @@ public function setManager($manager) /** * Get Manager * - * @return integer + * @return integer */ public function getManager() { diff --git a/src/InsaLan/TournamentBundle/Entity/ParticipantRepository.php b/src/InsaLan/TournamentBundle/Entity/ParticipantRepository.php index e8b47b3f..232dbb09 100644 --- a/src/InsaLan/TournamentBundle/Entity/ParticipantRepository.php +++ b/src/InsaLan/TournamentBundle/Entity/ParticipantRepository.php @@ -6,11 +6,11 @@ use Doctrine\ORM\Query; use Doctrine\Common\Collections\ArrayCollection; - class ParticipantRepository extends EntityRepository { - public function findByUser(\InsaLan\UserBundle\Entity\User $u) { + public function findByUser(\InsaLan\UserBundle\Entity\User $u) + { $em = $this->getEntityManager(); $query = $em->createQuery(" @@ -56,18 +56,18 @@ public function findByUser(\InsaLan\UserBundle\Entity\User $u) { return new ArrayCollection(array_merge($result1, $result2, $result3)); - } - public function findOneByUserAndTournament(\InsaLan\UserBundle\Entity\User $u, Tournament $t) { + public function findOneByUserAndTournament(\InsaLan\UserBundle\Entity\User $u, Tournament $t) + { $participants = $this->findByUser($u); // TODO : do this is SQL only (when stable) - foreach($participants as $p) { - if($p->getTournament()->getId() === $t->getId()) + foreach ($participants as $p) { + if ($p->getTournament()->getId() === $t->getId()) { return $p; + } } return null; } - } diff --git a/src/InsaLan/TournamentBundle/Entity/Player.php b/src/InsaLan/TournamentBundle/Entity/Player.php index 24d41756..8c635135 100644 --- a/src/InsaLan/TournamentBundle/Entity/Player.php +++ b/src/InsaLan/TournamentBundle/Entity/Player.php @@ -65,7 +65,8 @@ class Player extends Participant protected $pendingTournament; // this is a temporary variable when a player has not validated its account, and/or is waiting for a team. - public function getParticipantType() { + public function getParticipantType() + { return "player"; } @@ -84,7 +85,7 @@ public function __construct() /** * Get id * - * @return integer + * @return integer */ public function getId() { @@ -95,9 +96,10 @@ public function getId() /** * Get name * - * @return string + * @return string */ - public function getName() { + public function getName() + { if (isset($this->gameName)) { return $this->gameName; } else { @@ -122,7 +124,7 @@ public function setUser(\InsaLan\UserBundle\Entity\User $user = null) /** * Get user * - * @return \InsaLan\UserBundle\Entity\User + * @return \InsaLan\UserBundle\Entity\User */ public function getUser() { @@ -183,7 +185,7 @@ public function setTournament(\InsaLan\TournamentBundle\Entity\Tournament $tourn /** * Get tournament * - * @return \InsaLan\TournamentBundle\Entity\Tournament + * @return \InsaLan\TournamentBundle\Entity\Tournament */ public function getTournament() { @@ -216,7 +218,7 @@ public function removeGroup(\InsaLan\TournamentBundle\Entity\Group $groups) /** * Get groups * - * @return \Doctrine\Common\Collections\Collection + * @return \Doctrine\Common\Collections\Collection */ public function getGroups() { @@ -228,21 +230,24 @@ public function getGroups() * * @return String */ - public function __toString() { + public function __toString() + { return $this->getName(); } /** * is set */ - public function isNamed($type) { + public function isNamed($type) + { return $this->gameName !== null; } /** * is validated */ - public function isValidated($type) { + public function isValidated($type) + { return $this->gameValidated; } @@ -272,7 +277,7 @@ public function removeTeam(\InsaLan\TournamentBundle\Entity\Team $team) /** * Get team * - * @return \Doctrine\Common\Collections\Collection + * @return \Doctrine\Common\Collections\Collection */ public function getTeam() { @@ -282,14 +287,16 @@ public function getTeam() /** * Is Registered For Tournament */ - public function isRegisteredForTournament($id) { + public function isRegisteredForTournament($id) + { return $this->getTeamByTournamentId($id) !== null; } /** * Get team by tournament id */ - public function getTeamByTournamentId($id) { + public function getTeamByTournamentId($id) + { foreach ($this->team as $team) { if ($team->getTournament()->getId() == $id) { return $team; @@ -314,7 +321,7 @@ public function setGameName($gameName) /** * Get gameName * - * @return string + * @return string */ public function getGameName() { @@ -337,7 +344,7 @@ public function setGameId($gameId) /** * Get gameId * - * @return integer + * @return integer */ public function getGameId() { @@ -360,7 +367,7 @@ public function setGameValidated($gameValidated) /** * Get gameValidated * - * @return boolean + * @return boolean */ public function getGameValidated() { @@ -383,7 +390,7 @@ public function setGameAvatar($gameAvatar) /** * Get gameAvatar * - * @return integer + * @return integer */ public function getGameAvatar() { @@ -407,7 +414,7 @@ public function setPendingTournament(\InsaLan\TournamentBundle\Entity\Tournament /** * Get pendingTournament * - * @return \InsaLan\TournamentBundle\Entity\Tournament + * @return \InsaLan\TournamentBundle\Entity\Tournament */ public function getPendingTournament() { @@ -430,7 +437,7 @@ public function setPaymentDone($paymentDone) /** * Get paymentDone * - * @return boolean + * @return boolean */ public function getPaymentDone() { @@ -440,13 +447,15 @@ public function getPaymentDone() public function getTeamForTournament(Tournament $tournament) { foreach ($this->team as $t) { - if ($t->getTournament()->getId() == $tournament->getId()) + if ($t->getTournament()->getId() == $tournament->getId()) { return $t; + } } return null; } - public function isOk() { + public function isOk() + { return $this->paymentDone && $this->gameValidated; } @@ -466,11 +475,10 @@ public function setArrived($arrived) /** * Get arrived * - * @return boolean + * @return boolean */ public function getArrived() { return $this->arrived; } - } diff --git a/src/InsaLan/TournamentBundle/Entity/PlayerRepository.php b/src/InsaLan/TournamentBundle/Entity/PlayerRepository.php index b27e35b1..9e319624 100644 --- a/src/InsaLan/TournamentBundle/Entity/PlayerRepository.php +++ b/src/InsaLan/TournamentBundle/Entity/PlayerRepository.php @@ -6,11 +6,11 @@ use Doctrine\ORM\Query; use Doctrine\Common\Collections\ArrayCollection; - class PlayerRepository extends EntityRepository { - public function findOneByUserAndPendingTournament(\InsaLan\UserBundle\Entity\User $u, Tournament $t) { + public function findOneByUserAndPendingTournament(\InsaLan\UserBundle\Entity\User $u, Tournament $t) + { $q = $this->createQueryBuilder('p') ->where('p.user = :user AND p.pendingTournament = :tournament') @@ -19,14 +19,13 @@ public function findOneByUserAndPendingTournament(\InsaLan\UserBundle\Entity\Use try { return $q->getQuery()->getSingleResult(); - } - catch(\Exception $e) { + } catch (\Exception $e) { return null; } - } - public function getPlayersForTournament(Tournament $tournament) { + public function getPlayersForTournament(Tournament $tournament) + { $em = $this->getEntityManager(); $q = $this->createQueryBuilder('p') @@ -36,7 +35,8 @@ public function getPlayersForTournament(Tournament $tournament) { return $q->getQuery()->execute(); } - public function getAllPlayersForTournament(Tournament $tournament) { + public function getAllPlayersForTournament(Tournament $tournament) + { $em = $this->getEntityManager(); @@ -63,14 +63,14 @@ public function getAllPlayersForTournament(Tournament $tournament) { $players = $q->getQuery()->execute(); $out = array(); - foreach($players as $player) { - if($player->getValidated() === Participant::STATUS_VALIDATED) { + foreach ($players as $player) { + if ($player->getValidated() === Participant::STATUS_VALIDATED) { $out[] = $player; continue; } - foreach($player->getTeam() as $team) { - if($team->getValidated() === Participant::STATUS_VALIDATED) { + foreach ($player->getTeam() as $team) { + if ($team->getValidated() === Participant::STATUS_VALIDATED) { $out[] = $player; break; } @@ -80,7 +80,8 @@ public function getAllPlayersForTournament(Tournament $tournament) { return $out; } - public function getWaitingPlayer(Tournament $t) { + public function getWaitingPlayer(Tournament $t) + { $q = $this->createQueryBuilder('p') ->where('p.tournament = :tournament AND p.validated = :state') @@ -91,11 +92,8 @@ public function getWaitingPlayer(Tournament $t) { try { return $q->getQuery()->getSingleResult(); - } - catch(\Exception $e) { + } catch (\Exception $e) { return null; } - } - } diff --git a/src/InsaLan/TournamentBundle/Entity/Round.php b/src/InsaLan/TournamentBundle/Entity/Round.php index d484629e..f3e02031 100644 --- a/src/InsaLan/TournamentBundle/Entity/Round.php +++ b/src/InsaLan/TournamentBundle/Entity/Round.php @@ -76,7 +76,7 @@ public function getGroup() } public function getExtraInfos() - { + { return $this->getMatch()->getExtraInfos(); } @@ -95,10 +95,11 @@ public function getReplayFile() public function setReplayFile(UploadedFile $file = null) { $this->replayFile = $file; - if($file === null) + if ($file === null) { $this->setReplay(null); - else + } else { $this->setReplay($this->getFileName()); + } } /** @@ -132,7 +133,7 @@ public function uploadFile() public function getFullReplay() { - if(!$this->getReplay()) { + if (!$this->getReplay()) { return null; } @@ -146,10 +147,13 @@ private function getFileName() private function removeReplayFile($name) { - if(!$name) return; + if (!$name) { + return; + } $name = self::UPLOAD_PATH.DIRECTORY_SEPARATOR.$name; - if (file_exists($name)) + if (file_exists($name)) { unlink($name); + } } // End of Replay Upload managemet diff --git a/src/InsaLan/TournamentBundle/Entity/Team.php b/src/InsaLan/TournamentBundle/Entity/Team.php index 02dafd61..3f63eb10 100644 --- a/src/InsaLan/TournamentBundle/Entity/Team.php +++ b/src/InsaLan/TournamentBundle/Entity/Team.php @@ -61,7 +61,8 @@ class Team extends Participant protected $plainPassword; - public function getParticipantType() { + public function getParticipantType() + { return "team"; } @@ -74,7 +75,7 @@ public function __construct() /** * Get id * - * @return integer + * @return integer */ public function getId() { @@ -88,7 +89,7 @@ public function getId() * @return Team */ public function setPassword($password) - { + { $this->password = $password; @@ -98,7 +99,7 @@ public function setPassword($password) /** * Get password * - * @return string + * @return string */ public function getPassword() { @@ -156,7 +157,7 @@ public function setName($name) /** * Get name * - * @return string + * @return string */ public function getName() { @@ -171,7 +172,7 @@ public function getName() * @return Team */ public function addPlayer(\InsaLan\TournamentBundle\Entity\Player $players) - { + { if ($this->getPlayers()->count() >= $this->getTournament()->getTeamMaxPlayer()) { throw new \InsaLan\TournamentBundle\Exception\ControllerException("Cette équipe est pleine."); @@ -196,7 +197,7 @@ public function removePlayer(\InsaLan\TournamentBundle\Entity\Player $players) /** * Get players * - * @return \Doctrine\Common\Collections\Collection + * @return \Doctrine\Common\Collections\Collection */ public function getPlayers() { @@ -211,8 +212,9 @@ public function getPlayers() public function haveInPlayers(\InsaLan\TournamentBundle\Entity\Player $player) { foreach ($this->players as $teamPlayer) { - if($teamPlayer === $player) + if ($teamPlayer === $player) { return true; + } } return false; } @@ -233,7 +235,7 @@ public function setCaptain(\InsaLan\TournamentBundle\Entity\Player $captain = nu /** * Get captain * - * @return \InsaLan\TournamentBundle\Entity\Player + * @return \InsaLan\TournamentBundle\Entity\Player */ public function getCaptain() { @@ -256,7 +258,7 @@ public function setTournament(\InsaLan\TournamentBundle\Entity\Tournament $tourn /** * Get tournament * - * @return \InsaLan\TournamentBundle\Entity\Tournament + * @return \InsaLan\TournamentBundle\Entity\Tournament */ public function getTournament() { @@ -289,7 +291,7 @@ public function removeGroup(\InsaLan\TournamentBundle\Entity\Group $groups) /** * Get groups * - * @return \Doctrine\Common\Collections\Collection + * @return \Doctrine\Common\Collections\Collection */ public function getGroups() { @@ -301,7 +303,7 @@ public function getGroups() * * @return Team */ - public function __toString() + public function __toString() { return $this->name; } @@ -335,7 +337,7 @@ public function setLastUpdated($lastUpdated) /** * Get lastUpdated * - * @return integer + * @return integer */ public function getLastUpdated() { diff --git a/src/InsaLan/TournamentBundle/Entity/TeamRepository.php b/src/InsaLan/TournamentBundle/Entity/TeamRepository.php index 9d37dfd4..83daf80b 100644 --- a/src/InsaLan/TournamentBundle/Entity/TeamRepository.php +++ b/src/InsaLan/TournamentBundle/Entity/TeamRepository.php @@ -9,7 +9,8 @@ class TeamRepository extends EntityRepository { - public function getAllTeams() { + public function getAllTeams() + { $em = $this->getEntityManager(); $query = $em->createQuery(" @@ -22,7 +23,8 @@ public function getAllTeams() { return $query->getResult(); } - public function getTeamsForTournament(Tournament $t) { + public function getTeamsForTournament(Tournament $t) + { $em = $this->getEntityManager(); $query = $em->createQuery(" @@ -43,7 +45,8 @@ public function getTeamsForTournament(Tournament $t) { * @param Tournament $t Tournament to look into * @return Team The matched team, if any */ - public function findOneByNameAndTournament($team_name, Tournament $t) { + public function findOneByNameAndTournament($team_name, Tournament $t) + { $em = $this->getEntityManager(); $query = $em->createQuery(" @@ -58,13 +61,13 @@ public function findOneByNameAndTournament($team_name, Tournament $t) { try { return $query->getSingleResult(); - } - catch(\Exception $e) { + } catch (\Exception $e) { return null; } } - public function getWaitingTeam(Tournament $t) { + public function getWaitingTeam(Tournament $t) + { $q = $this->createQueryBuilder('t') ->where('t.tournament = :tournament AND t.validated = :state') @@ -75,11 +78,9 @@ public function getWaitingTeam(Tournament $t) { try { return $q->getQuery()->getSingleResult(); - } - catch(\Exception $e) { + } catch (\Exception $e) { return null; } - } diff --git a/src/InsaLan/TournamentBundle/Entity/Tournament.php b/src/InsaLan/TournamentBundle/Entity/Tournament.php index da96377b..c7e010ea 100644 --- a/src/InsaLan/TournamentBundle/Entity/Tournament.php +++ b/src/InsaLan/TournamentBundle/Entity/Tournament.php @@ -136,8 +136,8 @@ class Tournament * @ORM\Column(type="string", nullable=false) */ protected $currency; - - /** + + /** * @ORM\Column(type="string", nullable=false) */ protected $loginType; @@ -147,57 +147,68 @@ class Tournament */ protected $playerInfos; - public function isOpenedInFuture() { + public function isOpenedInFuture() + { $now = new \DateTime(); return $this->registrationOpen > $now; } - public function isOpenedNow() { + public function isOpenedNow() + { $now = new \DateTime(); return $this->registrationOpen <= $now && $this->registrationClose >= $now; } - public function isOpenedInPast() { + public function isOpenedInPast() + { $now = new \DateTime(); return $this->registrationClose < $now; } - public function isPending() { + public function isPending() + { $now = new \DateTime(); return $this->tournamentOpen > $now; } - public function isPlaying() { + public function isPlaying() + { $now = new \DateTime(); return $this->tournamentOpen <= $now && $this->tournamentClose >= $now; } - public function isClosed() { + public function isClosed() + { $now = new \DateTime(); return $this->tournamentClose < $now; } - public function isFull() { + public function isFull() + { return $this->getFreeSlots() === 0; } - public function isLocked() { + public function isLocked() + { return $this->locked != null; } - public function checkLocked($authToken) { + public function checkLocked($authToken) + { return $this->locked === $authToken; } - public function getValidatedSlots() { + public function getValidatedSlots() + { $nb = 0; - foreach($this->getParticipants() as $p) { + foreach ($this->getParticipants() as $p) { $nb += ($p->getValidated() === Participant::STATUS_VALIDATED ? 1 : 0); } return $nb; } - public function getFreeSlots() { + public function getFreeSlots() + { return $this->registrationLimit - $this->getValidatedSlots(); } @@ -281,8 +292,7 @@ public function onPostUpdate() public function onPreRemove() { $name = self::UPLOAD_PATH.DIRECTORY_SEPARATOR.$this->getId().'.png'; - if (file_exists($name)) - { + if (file_exists($name)) { unlink($name); } } @@ -573,11 +583,13 @@ protected function getUploadRootDir() return __DIR__.'/../../../../web/'.$this->getUploadDir(); } - public function setFileName() { + public function setFileName() + { $this->logoPath = sha1(uniqid(mt_rand(), true)).'.'.$this->file->guessExtension(); } - public function upload() { + public function upload() + { if (null === $this->file) { return; } @@ -867,7 +879,7 @@ public function getRules() { return $this->rules; } - /** + /** * Set rules * * @param string $rules diff --git a/src/InsaLan/TournamentBundle/Entity/TournamentRepository.php b/src/InsaLan/TournamentBundle/Entity/TournamentRepository.php index 6b778a81..735adf5e 100644 --- a/src/InsaLan/TournamentBundle/Entity/TournamentRepository.php +++ b/src/InsaLan/TournamentBundle/Entity/TournamentRepository.php @@ -9,7 +9,8 @@ class TournamentRepository extends EntityRepository { - public function findThisYearTournaments() { + public function findThisYearTournaments() + { $query = $this->createQueryBuilder('t') ->leftJoin('t.participants', 'p') ->addSelect('p') @@ -21,7 +22,8 @@ public function findThisYearTournaments() { ->getQuery(); return $query->getResult(); } - public function findOpened() { + public function findOpened() + { $query = $this->createQueryBuilder('t') ->where('t.registrationOpen <= :now AND t.registrationClose >= :now') ->setParameter('now', new \DateTime()) @@ -29,10 +31,11 @@ public function findOpened() { return $query->getResult(); } - public function getFreeSlots($tournamentId) { + public function getFreeSlots($tournamentId) + { $tournament = $this->findOneById($tournamentId); $freeSlots = $tournament->getRegistrationLimit(); - foreach($tournament->getParticipants() as $participant) { + foreach ($tournament->getParticipants() as $participant) { if ($participant->getValidated() === Participant::STATUS_VALIDATED) { $freeSlots--; } @@ -40,10 +43,11 @@ public function getFreeSlots($tournamentId) { return $freeSlots; } - public function selectWaitingParticipant($tournamentId) { + public function selectWaitingParticipant($tournamentId) + { $tournament = $this->findOneById($tournamentId); $participants = array(); - foreach($tournament->getParticipants() as $participant) { + foreach ($tournament->getParticipants() as $participant) { if ($participant->getValidated() === Participant::STATUS_WAITING) { $participants[] = $participant; } @@ -59,7 +63,8 @@ public function selectWaitingParticipant($tournamentId) { * @param Tournament $t * @return Associative array (integer=>true) */ - public function getUnavailablePlacements(Tournament $t) { + public function getUnavailablePlacements(Tournament $t) + { $em = $this->getEntityManager(); $res = $em->createQuery(" SELECT DISTINCT p.placement FROM InsaLanTournamentBundle:Participant p @@ -68,10 +73,9 @@ public function getUnavailablePlacements(Tournament $t) { ->getResult(); $out = array(); - foreach($res as $p) { + foreach ($res as $p) { $out[$p["placement"]] = true; } return $out; } - } diff --git a/src/InsaLan/TournamentBundle/Service/Placement.php b/src/InsaLan/TournamentBundle/Service/Placement.php index 1bef990c..71d69ac4 100644 --- a/src/InsaLan/TournamentBundle/Service/Placement.php +++ b/src/InsaLan/TournamentBundle/Service/Placement.php @@ -17,7 +17,8 @@ class Placement { - public function getStructure() { + public function getStructure() + { $structure = array(); // game id x y w h $structure[] = array("lol2017", 1, 0, 0, 5, 1); @@ -119,11 +120,11 @@ public function getStructure() { $hs = 1; // rightmost table - for($j = 0; $j < 16; $j++) { + for ($j = 0; $j < 16; $j++) { $structure[] = array("hs2017", $hs++, 33, $j, 1, 1); $structure[] = array("hs2017", $hs++, 34, $j, 1, 1); } return $structure; } -} \ No newline at end of file +} diff --git a/src/InsaLan/TournamentBundle/Service/PvpNet.php b/src/InsaLan/TournamentBundle/Service/PvpNet.php index 7c46719b..19a9d1d5 100644 --- a/src/InsaLan/TournamentBundle/Service/PvpNet.php +++ b/src/InsaLan/TournamentBundle/Service/PvpNet.php @@ -28,16 +28,19 @@ public function __construct(Lol $API) public function getGameResult(Team $teamA, Team $teamB, $dateLimit = null) { - if($dateLimit === null) + if ($dateLimit === null) { $dateLimit = time() - 3600 * 24; //One day + } - foreach($teamA->getPlayers()->toArray() as $summoner) - { + foreach ($teamA->getPlayers()->toArray() as $summoner) { $games = $this->API->game()->recent($summoner->getGameId()); - foreach($games as $game) - { - if($game->invalid) continue; - if(intval($game->createDate / 1000) < $dateLimit) continue; + foreach ($games as $game) { + if ($game->invalid) { + continue; + } + if (intval($game->createDate / 1000) < $dateLimit) { + continue; + } $teamACode = intval($game->stats->team); $teamBCode = ($teamACode === 100 ? 200 : 100); @@ -54,16 +57,14 @@ public function getGameResult(Team $teamA, Team $teamB, $dateLimit = null) if ($player->teamId === $teamACode && $this->isSummonerInTeam($player->summonerId, $teamA)) { $teamAChecked++; - } - elseif ($player->teamId === $teamBCode && $this->isSummonerInTeam($player->summonerId, $teamB)) { + } elseif ($player->teamId === $teamBCode && $this->isSummonerInTeam($player->summonerId, $teamB)) { $teamBChecked++; - } - else { + } else { break; } } - if($teamAChecked === 5 && $teamBChecked === 5) { + if ($teamAChecked === 5 && $teamBChecked === 5) { // We have found the right game, and it's correct :) $data = $this->API->match()->match($game->gameId, false)->raw(); @@ -82,7 +83,6 @@ public function getGameResult(Team $teamA, Team $teamB, $dateLimit = null) return array($winner, json_encode($data)); } } - } // Not found @@ -127,12 +127,12 @@ public function generateUrl($conf = array()) private function isSummonerInTeam($summonerId, Team $team) { - foreach($team->getPlayers()->toArray() as $player) { - if($player->getGameId() === $summonerId) return true; + foreach ($team->getPlayers()->toArray() as $player) { + if ($player->getGameId() === $summonerId) { + return true; + } } return false; } - } -?> diff --git a/src/InsaLan/TournamentBundle/Subscriber/ParticipantValidator.php b/src/InsaLan/TournamentBundle/Subscriber/ParticipantValidator.php index ccd008a0..23fe251c 100644 --- a/src/InsaLan/TournamentBundle/Subscriber/ParticipantValidator.php +++ b/src/InsaLan/TournamentBundle/Subscriber/ParticipantValidator.php @@ -2,7 +2,7 @@ namespace InsaLan\TournamentBundle\Subscriber; -use Doctrine\Common\EventSubscriber; +use Doctrine\Common\EventSubscriber; use Doctrine\ORM\Event\LifecycleEventArgs; use Doctrine\ORM\Event\PostFlushEventArgs; use InsaLan\TournamentBundle\Entity\Team; @@ -11,7 +11,8 @@ use InsaLan\InsaLanBundle\Service\FreeSlots; class ParticipantValidator implements EventSubscriber -{ +{ + private $updated_participants; public function __construct() @@ -30,87 +31,77 @@ public function getSubscribedEvents() } public function prePersist(LifecycleEventArgs $args) - { + { $this->preUpdate($args); } public function preUpdate(LifecycleEventArgs $args) - { + { $entity = $args->getEntity(); $em = $args->getEntityManager(); - if($entity instanceof Player) { - - if($entity->getTournament() !== null && $entity->getValidated() !== Participant::STATUS_VALIDATED) { - $this->validatePlayer($entity,$em); + if ($entity instanceof Player) { + if ($entity->getTournament() !== null && $entity->getValidated() !== Participant::STATUS_VALIDATED) { + $this->validatePlayer($entity, $em); } - foreach($entity->getTeam() as $t) { - $this->teamLogic($t,$em); + foreach ($entity->getTeam() as $t) { + $this->teamLogic($t, $em); } } } //Team Validation depends only of Players, so we can reasonnably execute it only when a user is updated. I guess. - private function teamLogic($team,$em) { - if ($team->getCaptain() === null && $team->getPlayers()->count() > 0) { + private function teamLogic($team, $em) + { + if ($team->getCaptain() === null && $team->getPlayers()->count() > 0) { $team->setCaptain($team->getPlayers()->first()); $this->updated_participants[] = $team; } - if($team->getValidated() !== Participant::STATUS_VALIDATED) - $this->validateTeam($team,$em); - - else - $this->unValidateTeam($team,$em); + if ($team->getValidated() !== Participant::STATUS_VALIDATED) { + $this->validateTeam($team, $em); + } else { + $this->unValidateTeam($team, $em); + } } public function preRemove(LifecycleEventArgs $args) - { + { $entity = $args->getEntity(); - if($entity instanceof Participant) { - - if($entity->getTournament() !== null && $entity->getValidated() === Participant::STATUS_VALIDATED) { - + if ($entity instanceof Participant) { + if ($entity->getTournament() !== null && $entity->getValidated() === Participant::STATUS_VALIDATED) { $em = $args->getEntityManager(); - if($entity instanceof Player) { - - + if ($entity instanceof Player) { $waitingPlayer = $em ->getRepository('InsaLanTournamentBundle:Player') ->getWaitingPlayer($entity->getTournament()); - if($waitingPlayer) { + if ($waitingPlayer) { $waitingPlayer->setValidated(Participant::STATUS_VALIDATED); $this->updated_participants[] = $waitingPlayer; } - } else { - $waitingTeam = $em ->getRepository('InsaLanTournamentBundle:Team') ->getWaitingTeam($entity->getTournament()); - if($waitingTeam) { + if ($waitingTeam) { $waitingTeam->setValidated(Participant::STATUS_VALIDATED); $this->updated_participants[] = $waitingTeam; } - } } - } - - } public function postFlush(PostFlushEventArgs $args) { - if($this->updated_participants) { //execute the save if needed. + if ($this->updated_participants) { //execute the save if needed. $em = $args->getEntityManager(); - foreach($this->updated_participants as $team) { + foreach ($this->updated_participants as $team) { $em->persist($team); } $this->updated_participants = []; //put this ABSOLUTELY BEFORE the flush. @@ -118,60 +109,67 @@ public function postFlush(PostFlushEventArgs $args) } } - protected function validatePlayer($player,$em) { + protected function validatePlayer($player, $em) + { - if(!$player->getPaymentDone() && $player->getTournament()->getWebPrice() > 0) return; + if (!$player->getPaymentDone() && $player->getTournament()->getWebPrice() > 0) { + return; + } $freeSlots = $em ->getRepository('InsaLanTournamentBundle:Tournament') ->getFreeSlots($player->getTournament()->getId()); - if($freeSlots > 0) + if ($freeSlots > 0) { $player->setValidated(Participant::STATUS_VALIDATED); - else + } else { $player->setValidated(Participant::STATUS_WAITING); + } $this->updated_participants[] = $player; //register for further save } - protected function validateTeam($team, $em) { + protected function validateTeam($team, $em) + { - if($team->getPlayers()->count() >= $team->getTournament()->getTeamMinPlayer()) { - + if ($team->getPlayers()->count() >= $team->getTournament()->getTeamMinPlayer()) { // Check players payments $minPaymentNumbers = floor($team->getTournament()->getTeamMinPlayer() / 2) + 1; $sumPayments = 0; - foreach($team->getPlayers() as $p) { - if($p->getPaymentDone()) $sumPayments++; + foreach ($team->getPlayers() as $p) { + if ($p->getPaymentDone()) { + $sumPayments++; + } } - if($sumPayments < $minPaymentNumbers && $team->getTournament()->getWebPrice() > 0) return; + if ($sumPayments < $minPaymentNumbers && $team->getTournament()->getWebPrice() > 0) { + return; + } //Ready for validation $freeSlots = $em ->getRepository('InsaLanTournamentBundle:Tournament') ->getFreeSlots($team->getTournament()->getId()); - if($freeSlots > 0) + if ($freeSlots > 0) { $team->setValidated(Participant::STATUS_VALIDATED); - else + } else { $team->setValidated(Participant::STATUS_WAITING); + } $this->updated_participants[] = $team; } - - } - protected function unValidateTeam($team,$em) { + protected function unValidateTeam($team, $em) + { - if($team->getPlayers()->count() < $team->getTournament()->getTeamMinPlayer()) { - + if ($team->getPlayers()->count() < $team->getTournament()->getTeamMinPlayer()) { $waitingTeam = $em ->getRepository('InsaLanTournamentBundle:Team') ->getWaitingTeam($team->getTournament()); - if($waitingTeam) { + if ($waitingTeam) { $waitingTeam->setValidated(Participant::STATUS_VALIDATED); $this->updated_participants[] = $waitingTeam; } @@ -179,9 +177,5 @@ protected function unValidateTeam($team,$em) { $team->setValidated(Participant::STATUS_PENDING); $this->updated_participants[] = $team; } - } - } - -?> diff --git a/src/InsaLan/TournamentBundle/Validator/Constraint/ExistingLolId.php b/src/InsaLan/TournamentBundle/Validator/Constraint/ExistingLolId.php index 3e5727c2..50c35ab4 100644 --- a/src/InsaLan/TournamentBundle/Validator/Constraint/ExistingLolId.php +++ b/src/InsaLan/TournamentBundle/Validator/Constraint/ExistingLolId.php @@ -22,7 +22,8 @@ public function validatedBy() } } -class ExistingLolIdValidator extends ConstraintValidator { +class ExistingLolIdValidator extends ConstraintValidator +{ protected $apiLol; public function validate($value, Constraint $constraint) @@ -30,12 +31,12 @@ public function validate($value, Constraint $constraint) try { $apiSummoner = $this->apiLol->getApi()->summoner(); $rSummoner = $apiSummoner->info($value); - } catch(\Exception $e) { + } catch (\Exception $e) { $className = get_class($e); if ('GuzzleHttp\\Exception\\ClientException' === $className && 404 == $e->getResponse()->getStatusCode()) { $this->context->addViolation($constraint->message_not_found, array('%string%' => $value)); - } else if (0 === strpos($className, 'GuzzleHttp')) { + } elseif (0 === strpos($className, 'GuzzleHttp')) { $this->context->addViolation($constraint->message_api_error, array('%string%' => $value)); } else { throw $e; @@ -43,7 +44,8 @@ public function validate($value, Constraint $constraint) } } - public function setLolApi(Lol $apiLol) { + public function setLolApi(Lol $apiLol) + { $this->apiLol = $apiLol; } } diff --git a/src/InsaLan/UserBundle/Admin/DiscountAdmin.php b/src/InsaLan/UserBundle/Admin/DiscountAdmin.php index 37c9830f..7e1aa08a 100644 --- a/src/InsaLan/UserBundle/Admin/DiscountAdmin.php +++ b/src/InsaLan/UserBundle/Admin/DiscountAdmin.php @@ -38,5 +38,4 @@ protected function configureListFields(ListMapper $listMapper) ->add('amount') ; } - } diff --git a/src/InsaLan/UserBundle/Admin/MerchantOrderAdmin.php b/src/InsaLan/UserBundle/Admin/MerchantOrderAdmin.php index e1ac8a4a..e1ffe108 100644 --- a/src/InsaLan/UserBundle/Admin/MerchantOrderAdmin.php +++ b/src/InsaLan/UserBundle/Admin/MerchantOrderAdmin.php @@ -43,5 +43,4 @@ protected function configureRoutes(RouteCollection $collection) { $collection->remove('create'); } - } diff --git a/src/InsaLan/UserBundle/Admin/UserAdmin.php b/src/InsaLan/UserBundle/Admin/UserAdmin.php index 06fe821d..6339fa43 100644 --- a/src/InsaLan/UserBundle/Admin/UserAdmin.php +++ b/src/InsaLan/UserBundle/Admin/UserAdmin.php @@ -57,5 +57,4 @@ protected function configureListFields(ListMapper $listMapper) ->add('phoneNumber') ; } - } diff --git a/src/InsaLan/UserBundle/Controller/DefaultController.php b/src/InsaLan/UserBundle/Controller/DefaultController.php index a65da4d7..90ff8398 100644 --- a/src/InsaLan/UserBundle/Controller/DefaultController.php +++ b/src/InsaLan/UserBundle/Controller/DefaultController.php @@ -64,11 +64,11 @@ public function registerSteamIdAction(Request $request) $imageSrc = null; $routeDelete = null; $login = new SteamLogin(); - $url = $this->generateUrl('insalan_user_default_savesteamid', array('slug' => ''),UrlGeneratorInterface::ABSOLUTE_URL); + $url = $this->generateUrl('insalan_user_default_savesteamid', array('slug' => ''), UrlGeneratorInterface::ABSOLUTE_URL); $url = str_replace("http://", "https://", $url); $url = $login->url($url); - if($request->query->get('action') == 'remove') { + if ($request->query->get('action') == 'remove') { $em = $this->getDoctrine()->getManager(); $usr->setSteamId(null); $em->persist($usr); @@ -76,7 +76,7 @@ public function registerSteamIdAction(Request $request) return $this->redirect($this->generateUrl('insalan_user_default_registersteamid')); } - if($connectedAccount != null) { + if ($connectedAccount != null) { $routeDelete = $this->generateUrl('insalan_user_default_registersteamid'); $routeDelete = $routeDelete.'?action=remove'; $steamDetails = $usr->getSteamDetails($steamKey); @@ -104,15 +104,15 @@ public function saveSteamIdAction(Request $request) $callbackRoute = $this->get('session')->get('callbackRegisterApiRoute'); $callbackParams = $this->get('session')->get('callbackRegisterApiParams'); - if(isset($id)) { + if (isset($id)) { $usr->setSteamId($id); $em->persist($usr); $em->flush(); - if($callbackRoute != null) { + if ($callbackRoute != null) { $this->get('session')->set('callbackRegisterApiRoute', null); $this->get('session')->set('callbackRegisterApiParams', null); - return $this->redirect($this->generateUrl($callbackRoute,$callbackParams)); + return $this->redirect($this->generateUrl($callbackRoute, $callbackParams)); } $steamKey = $this->getParameter('steam_api_key'); @@ -142,7 +142,7 @@ public function registerBattleNetAction(Request $request) $authorize_uri = 'https://eu.battle.net/oauth/authorize'; $token_uri = 'https://eu.battle.net/oauth/token'; - if(isset($_GET['action']) && $_GET['action'] == 'remove') { + if (isset($_GET['action']) && $_GET['action'] == 'remove') { $em = $this->getDoctrine()->getManager(); $usr->setBattleTag(null); $em->persist($usr); @@ -150,7 +150,7 @@ public function registerBattleNetAction(Request $request) unset($_GET['code']); // just to be sure } $client = new Client($client_id, $client_secret); - if($usr->getBattleTag() != null) { + if ($usr->getBattleTag() != null) { return array('enregistre' => true, 'battletag' => $usr->getBattleTag()); } if (!isset($_GET['code'])) { @@ -162,7 +162,7 @@ public function registerBattleNetAction(Request $request) try { $response = $client->getAccessToken($token_uri, 'authorization_code', $params); $info = $response['result']; - if(isset($info) && isset($info['access_token'])) { + if (isset($info) && isset($info['access_token'])) { $client->setAccessToken($info['access_token']); $response = $client->fetch('https://eu.api.battle.net/account/user'); $em = $this->getDoctrine()->getManager(); @@ -173,11 +173,10 @@ public function registerBattleNetAction(Request $request) } else { return array('erreur' => true); } - } catch(\Exception $e) { + } catch (\Exception $e) { return array('erreur' => true); } } return null; } - } diff --git a/src/InsaLan/UserBundle/Entity/Discount.php b/src/InsaLan/UserBundle/Entity/Discount.php index 630257b0..72ed360b 100644 --- a/src/InsaLan/UserBundle/Entity/Discount.php +++ b/src/InsaLan/UserBundle/Entity/Discount.php @@ -41,7 +41,7 @@ class Discount /** * Get id * - * @return integer + * @return integer */ public function getId() { @@ -64,7 +64,7 @@ public function setName($name) /** * Get name * - * @return string + * @return string */ public function getName() { diff --git a/src/InsaLan/UserBundle/Entity/MerchantOrder.php b/src/InsaLan/UserBundle/Entity/MerchantOrder.php index af3bc4a8..16165ed4 100644 --- a/src/InsaLan/UserBundle/Entity/MerchantOrder.php +++ b/src/InsaLan/UserBundle/Entity/MerchantOrder.php @@ -41,7 +41,7 @@ class MerchantOrder /** * Get id * - * @return integer + * @return integer */ public function getId() { diff --git a/src/InsaLan/UserBundle/Entity/PaymentDetails.php b/src/InsaLan/UserBundle/Entity/PaymentDetails.php index 2d2a7249..6f93d87d 100644 --- a/src/InsaLan/UserBundle/Entity/PaymentDetails.php +++ b/src/InsaLan/UserBundle/Entity/PaymentDetails.php @@ -30,7 +30,8 @@ class PaymentDetails extends ArrayObject private $detailId = 0; - public function addPaymentDetail($name, $price, $description) { + public function addPaymentDetail($name, $price, $description) + { $i = $this->detailId++; $this["L_PAYMENTREQUEST_0_NAME$i"] = $name; $this["L_PAYMENTREQUEST_0_AMT$i"] = $price; @@ -41,7 +42,7 @@ public function addPaymentDetail($name, $price, $description) { /** * Get id * - * @return integer + * @return integer */ public function getId() { @@ -65,7 +66,7 @@ public function setUser(\InsaLan\UserBundle\Entity\User $user = null) /** * Get user * - * @return \InsaLan\UserBundle\Entity\User + * @return \InsaLan\UserBundle\Entity\User */ public function getUser() { @@ -88,7 +89,7 @@ public function setDiscount(\InsaLan\UserBundle\Entity\Discount $discount = null /** * Get discount * - * @return \InsaLan\UserBundle\Entity\Discount + * @return \InsaLan\UserBundle\Entity\Discount */ public function getDiscount() { diff --git a/src/InsaLan/UserBundle/Entity/User.php b/src/InsaLan/UserBundle/Entity/User.php index 3dc86974..29b2e787 100644 --- a/src/InsaLan/UserBundle/Entity/User.php +++ b/src/InsaLan/UserBundle/Entity/User.php @@ -51,7 +51,7 @@ public function __construct() protected $battleTag; /** - * @ORM\Column(type="date", nullable=true) + * @ORM\Column(type="date", nullable=true) */ private $birthdate; @@ -104,7 +104,7 @@ public function setFirstname($firstname) /** * Get firstname * - * @return string + * @return string */ public function getFirstname() { @@ -127,7 +127,7 @@ public function setLastname($lastname) /** * Get lastname * - * @return string + * @return string */ public function getLastname() { @@ -150,7 +150,7 @@ public function setPhoneNumber($phoneNumber) /** * Get phoneNumber * - * @return string + * @return string */ public function getPhoneNumber() { @@ -172,7 +172,7 @@ public function setSteamId($id) /** * Get steam id * - * @return string + * @return string */ public function getSteamId() { @@ -194,7 +194,7 @@ public function setBattleTag($tag) /** * Get battle tag (battle.net) * - * @return string + * @return string */ public function getBattleTag() { @@ -215,21 +215,22 @@ public function setBirthdate($birthdate) /** * Get birthdate * - * @return \DateTime + * @return \DateTime */ public function getBirthdate() { return $this->birthdate; } - public function getSteamDetails($steamKey) { - if($this->steamId == null) + public function getSteamDetails($steamKey) + { + if ($this->steamId == null) { return null; + } $json = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key='.$steamKey.'&steamids='.$this->steamId); - if($json != null) { + if ($json != null) { $obj = json_decode($json); return $obj->response->players[0]; - } return null; } diff --git a/src/InsaLan/UserBundle/Exception/ControllerException.php b/src/InsaLan/UserBundle/Exception/ControllerException.php index 65737786..f10f6b48 100644 --- a/src/InsaLan/UserBundle/Exception/ControllerException.php +++ b/src/InsaLan/UserBundle/Exception/ControllerException.php @@ -4,4 +4,4 @@ class ControllerException extends \Exception { -} \ No newline at end of file +} diff --git a/src/InsaLan/UserBundle/Service/Payment.php b/src/InsaLan/UserBundle/Service/Payment.php index 72963f42..9f18caff 100644 --- a/src/InsaLan/UserBundle/Service/Payment.php +++ b/src/InsaLan/UserBundle/Service/Payment.php @@ -13,20 +13,23 @@ use Payum\Paypal\ExpressCheckout\Nvp\Api; class Payment -{ +{ + private $payum; private $payumCheck; private $payumToken; private $paymentName = 'paypal_express_checkout_and_doctrine_orm'; - public function __construct($p, $pp, $ppp) { + public function __construct($p, $pp, $ppp) + { $this->payum = $p; $this->payumCheck = $pp; $this->payumToken = $ppp; } - public function getOrder($currency, $price) { + public function getOrder($currency, $price) + { $storage = $this->payum->getStorage('InsaLan\UserBundle\Entity\PaymentDetails'); @@ -38,7 +41,8 @@ public function getOrder($currency, $price) { return $order; } - public function getTargetUrl($order, $callbackRoute, $callbackParameters = null) { + public function getTargetUrl($order, $callbackRoute, $callbackParameters = null) + { $storage = $this->payum->getStorage('InsaLan\UserBundle\Entity\PaymentDetails'); @@ -57,21 +61,19 @@ public function getTargetUrl($order, $callbackRoute, $callbackParameters = null) $storage->updateModel($order); return $captureToken->getTargetUrl(); - } - public function check($request, $invalidate = false) { + public function check($request, $invalidate = false) + { $token = $this->payumCheck->verify($request); $payment = $this->payum->getPayment($token->getPaymentName()); - if($invalidate) + if ($invalidate) { $this->payumCheck->invalidate($token); + } $payment->execute($status = new GetHumanStatus($token)); return $status->isCaptured(); - } - - -} \ No newline at end of file +}