first() публичный статический Метод

Example: $array = array('one', 'two' 'three'); $first = Arrays::first($array); Result: one
public static first ( array $elements ) : mixed
$elements array
Результат mixed
Пример #1
0
 public static function callFunction($functionName, $parameters)
 {
     $db = self::getInstance();
     $bindParams = Arrays::toArray($parameters);
     $paramsQueryString = implode(',', array_pad(array(), sizeof($bindParams), '?'));
     return Arrays::first($db->query("SELECT {$functionName}({$paramsQueryString})", $parameters)->fetch());
 }
Пример #2
0
 private function removeTablePrefix($tableNameParts)
 {
     if (Arrays::first($tableNameParts) == $this->tablePrefix) {
         array_shift($tableNameParts);
     }
     return $tableNameParts;
 }
Пример #3
0
 public function __construct($httpCode, $errors, $headers = array())
 {
     $this->_httpCode = $httpCode;
     $this->_errors = Arrays::toArray($errors);
     $this->_headers = $headers;
     $firstError = Arrays::first($this->_errors);
     parent::__construct($firstError->getMessage(), $firstError->getCode());
 }
Пример #4
0
 /**
  * @test
  */
 public function shouldTraceInfoAboutHttpRequest()
 {
     //given
     $this->_createHttpTraceRequest('/request1', array('param1' => 1, 'param2' => 2));
     //when
     $queries = Arrays::first(Stats::queries());
     //then
     ArrayAssert::that($queries['request_params'][0])->hasSize(2)->containsKeyAndValue(array('param1' => 1, 'param2' => 2));
 }
Пример #5
0
 public static function resolve()
 {
     $accept = array_keys(RequestHeaders::accept()) ?: array('*/*');
     $supported = array('application/json' => 'application/json', 'application/xml' => 'application/xml', 'application/*' => 'application/json', 'text/html' => 'text/html', 'text/*' => 'text/html');
     $intersection = array_intersect($accept, array_keys($supported));
     if ($intersection) {
         return $supported[Arrays::first($intersection)];
     }
     return Arrays::getValue($supported, ContentType::value(), 'text/html');
 }
Пример #6
0
 /**
  * @inheritdoc
  */
 public function isScored($field, $multiplier)
 {
     $isScoredField = in_array($field, self::$SCORED_FIELDS);
     if ($isScoredField) {
         $sum = Hit::select('sum(multiplier)')->where(['game_user_id' => $this->game->current_game_user_id, 'field' => $field])->fetch();
         $hitCountBeforeCurrentHit = Arrays::first($sum) - $multiplier;
         return $hitCountBeforeCurrentHit < 3;
     }
     return false;
 }
Пример #7
0
 /**
  * @test
  */
 public function shouldCreateSelectQueryWithJoin()
 {
     // when
     $query = Query::select()->join('table', 'id', 'other_id', 'tab');
     // then
     $this->assertCount(1, $query->joinClauses);
     $join = Arrays::first($query->joinClauses);
     $this->assertEquals('id', $join->joinColumn);
     $this->assertEquals('table', $join->joinTable);
     $this->assertEquals('other_id', $join->joinedColumn);
 }
Пример #8
0
 /**
  * @test
  */
 public function shouldReturnCorrectRouteRule()
 {
     //given
     Route::get('/user/index', 'User#index');
     //when
     $route = Arrays::first(Route::getRoutes());
     //then
     $this->assertEquals('/user/index', $route->getUri());
     $this->assertEquals('User', $route->getController());
     $this->assertEquals('index', $route->getAction());
 }
Пример #9
0
 /**
  * @test
  */
 public function shouldEmitEventAfterHit()
 {
     //given
     $field = '20t';
     //when
     $this->post('/hit', ['field' => $field]);
     //then
     /** @var Event $event */
     $event = Arrays::first(Event::all());
     $this->assertEquals('hit', $event->name);
     $this->assertEquals('{"field":20,"multiplier":3,"scored":true,"winner":false,"shots_left":2}', $event->params);
 }
Пример #10
0
 public function execute()
 {
     if (empty($this->_models)) {
         return;
     }
     $this->_callBeforeSaveCallbacks();
     $metaInstance = Arrays::first($this->_models);
     $columns = $metaInstance->getFieldsWithoutPrimaryKey();
     $primaryKey = $metaInstance->getIdName();
     $table = $metaInstance->getTableName();
     $sql = DialectFactory::create()->batchInsert($table, $primaryKey, $columns, count($this->_models));
     $params = $this->_prepareParams($primaryKey);
     $ids = Arrays::flatten(Db::getInstance()->query($sql, $params)->fetchAll(PDO::FETCH_NUM));
     $this->_assignPrimaryKeys($primaryKey, $ids);
     $this->_callAfterSaveCallbacks();
 }
Пример #11
0
 public function extracting()
 {
     $selectors = func_get_args();
     $actual = array();
     if (count($selectors) == 1) {
         $selector = Arrays::first($selectors);
         $actual = Arrays::map($this->actual, Functions::extractExpression($selector, true));
     } else {
         foreach ($this->actual as $item) {
             $extracted = array();
             foreach ($selectors as $selector) {
                 $extracted[] = Functions::call(Functions::extractExpression($selector, true), $item);
             }
             $actual[] = $extracted;
         }
     }
     return self::that($actual);
 }
Пример #12
0
 private static function addRoute($method, $uri, $action, $requireAction = true, $options = array(), $isResource = false)
 {
     $methods = Arrays::toArray($method);
     if (self::$isDebug && $requireAction && self::$validate && self::existRouteRule($methods, $uri)) {
         $methods = implode(', ', $methods);
         throw new InvalidArgumentException('Route rule for method ' . $methods . ' and URI "' . $uri . '" already exists');
     }
     $elements = explode('#', $action);
     $controller = Arrays::first($elements);
     $actionToRule = Arrays::getValue($elements, 1);
     $routeRule = new RouteRule($method, $uri, $controller, $actionToRule, $requireAction, $options, $isResource);
     if ($routeRule->hasRequiredAction()) {
         throw new InvalidArgumentException('Route rule ' . $uri . ' required action');
     }
     self::$routes[] = $routeRule;
     foreach ($methods as $method) {
         self::$routeKeys[$method . $uri] = true;
     }
 }
Пример #13
0
 /**
  * @test
  */
 public function shouldGetHitsOnlyForPlayersInCurrentGame()
 {
     //given
     $user = User::create(['login' => 'test', 'password' => 'a']);
     $game1 = Game::create();
     $game1->addPlayer($user->getId());
     /** @var GameUser $gameUser1 */
     $gameUser1 = Arrays::first($game1->game_users);
     $game2 = Game::create();
     $game2->addPlayer($user->getId());
     /** @var GameUser $gameUser2 */
     $gameUser2 = Arrays::first($game2->game_users);
     Hit::createFor('4d', $gameUser1);
     Hit::createFor('15t', $gameUser2);
     //when
     $hits = Hit::findForGame($game1);
     //then
     Assert::thatArray($hits)->onProperty('field')->containsExactly('4');
 }
Пример #14
0
 public static function parse($data)
 {
     $array = array();
     $items = Arrays::filterNotBlank(explode(',', $data));
     foreach ($items as $item) {
         $elements = explode(';', $item);
         $media = Arrays::first($elements);
         $params = array_slice($elements, 1);
         list($type, $subtype) = Arrays::map(explode('/', $media), Functions::trim());
         $q = Arrays::getValue(self::extractParams($params), 'q');
         $array[] = array('type' => $type, 'subtype' => $subtype, 'q' => $q);
     }
     usort($array, '\\Ouzo\\Http\\AcceptHeaderParser::_compare');
     return Arrays::toMap($array, function ($input) {
         return $input['type'] . '/' . $input['subtype'];
     }, function ($input) {
         return $input['q'];
     });
 }
Пример #15
0
 public function process()
 {
     $post = $this->post;
     $filterLogin = Arrays::filter($this->getElements(), function ($element) use($post) {
         if ($element->user_name == $post->user_auth->user_name && $element->password == $post->user_auth->password) {
             return $element;
         }
         return null;
     });
     if (!$filterLogin) {
         $response = new stdClass();
         $response->name = 'Invalid Login';
         $response->number = '10';
         $response->description = 'Login attempt failed please check the username and password';
         $this->response = $response;
     } else {
         $user = Arrays::first($filterLogin);
         $response = new stdClass();
         $response->id = $user->id;
         $this->response = $response;
     }
     return $this;
 }
Пример #16
0
 public function createController()
 {
     $routeRule = Arrays::first(Route::getRoutes());
     return SampleController::createInstance($routeRule);
 }
Пример #17
0
 /**
  * @test
  */
 public function shouldParseObjectWithClassName()
 {
     //given
     $parser = $this->parser('object $user { className \\Foo\\Bar\\Baz }');
     //when
     $nodes = $parser->S();
     //then
     Assert::thatArray($nodes)->extracting('type', 'name', 'isArray')->containsExactly(array('object'), array('$user'), array(false));
     /** @var Node $node */
     $node = Arrays::first($nodes);
     Assert::thatArray($node->getElements())->extracting('type', 'name', 'isArray', 'elements')->containsExactly(array('className'), array('\\Foo\\Bar\\Baz'), array(false), array(array()));
 }
Пример #18
0
 /**
  * @test
  */
 public function shouldGetFirstKeyString()
 {
     //given
     $array = array('foo' => 'bar', 2 => 'example');
     //when
     $first = Arrays::first($array);
     // then
     Assert::thatString($first)->isEqualTo('bar');
 }
Пример #19
0
 /**
  * @test
  */
 public function shouldStubMethodWithCallback()
 {
     //given
     $mock = Mock::mock();
     Mock::when($mock)->method(Mock::any())->thenAnswer(function (MethodCall $methodCall) {
         return $methodCall->name . ' ' . Arrays::first($methodCall->arguments);
     });
     //when
     $result = $mock->method('arg');
     //then
     $this->assertEquals("method arg", $result);
 }
Пример #20
0
 /**
  * Converts file size in bytes to a string with unit.
  *
  * Example:
  * <code>
  * $unit = Files::convertUnitFileSize(146432);
  * </code>
  * Result:
  * <code>
  * 143 KB
  * </code>
  *
  * @param int $size
  * @return string
  */
 public static function convertUnitFileSize($size)
 {
     $units = array(" B", " KB", " MB", " GB");
     $calculatedSize = $size;
     $unit = Arrays::first($units);
     if ($size) {
         $calculatedSize = round($size / pow(1024, $i = (int) floor(log($size, 1024))), 2);
         $unit = $units[$i];
     }
     return $calculatedSize . $unit;
 }
Пример #21
0
 private static function getFromServer()
 {
     return Arrays::first(explode(';', Arrays::getValue($_SERVER, 'CONTENT_TYPE')));
 }
Пример #22
0
 /**
  * @test
  */
 public function shouldTraceRequestInfo()
 {
     //given
     Config::overrideProperty('debug')->with(true);
     Route::resource('restful');
     $this->get('/restful?param=1');
     //when
     $queries = Arrays::first(Stats::queries());
     //then
     ArrayAssert::that($queries['request_params'][0])->hasSize(1)->containsKeyAndValue(array('param' => 1));
 }
Пример #23
0
 /**
  * @test
  */
 public function shouldNotCallMapFunctionOnSkippedElements()
 {
     //given
     $iterator = new \ArrayIterator(array(1, 2, 3));
     $mapper = Mock::create();
     Mock::when($mapper)->map(Mock::anyArgList())->thenAnswer(function (MethodCall $methodCall) {
         return Arrays::first($methodCall->arguments);
     });
     //when
     $result = FluentIterator::from($iterator)->map(function ($elem) use($mapper) {
         return $mapper->map($elem);
     })->skip(1)->limit(1);
     //then
     $this->assertEquals(array(2), array_values($result->toArray()));
     Mock::verify($mapper)->neverReceived()->map(1);
     Mock::verify($mapper)->neverReceived()->map(3);
 }
Пример #24
0
 private function removeMatchedCallIfMultipleResults($matching)
 {
     if (count($matching) > 1) {
         $this->removeStubbedCall(Arrays::first($matching));
     }
 }
Пример #25
0
 /**
  * @test
  */
 public function shouldJoinMultipleModels()
 {
     //given
     $category1 = Category::create(array('name' => 'phones'));
     $product1 = Product::create(array('name' => 'sony', 'id_category' => $category1->getId()));
     $order1 = Order::create(array('name' => 'order#1'));
     OrderProduct::create(array('id_order' => $order1->getId(), 'id_product' => $product1->getId()));
     $category2 = Category::create(array('name' => 'phones'));
     $product2 = Product::create(array('name' => 'sony', 'id_category' => $category2->getId()));
     $order2 = Order::create(array('name' => 'order#2'));
     OrderProduct::create(array('id_order' => $order2->getId(), 'id_product' => $product2->getId()));
     //when
     $orderProducts = OrderProduct::join('product')->join('order')->where(array('products.id' => $product1->getId()))->fetchAll();
     //then
     $this->assertCount(1, $orderProducts);
     $find = Arrays::first($orderProducts);
     $this->assertEquals('order#1', $find->order->name);
     $this->assertEquals('sony', $find->product->name);
     $this->assertEquals('phones', $find->product->category->name);
 }