PocketMine-MP  1.4 - API 1.10.0
 All Classes Namespaces Functions Variables Pages
TextWrapper.php
1 <?php
2 
3 /*
4  *
5  * ____ _ _ __ __ _ __ __ ____
6  * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7  * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8  * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9  * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU Lesser General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * @author PocketMine Team
17  * @link http://www.pocketmine.net/
18  *
19  *
20 */
21 
22 namespace pocketmine\utils;
23 
24 abstract class TextWrapper{
25 
26  private static $characterWidths = [
27  4, 2, 5, 6, 6, 6, 6, 3, 5, 5, 5, 6, 2, 6, 2, 6,
28  6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 2, 2, 5, 6, 5, 6,
29  7, 6, 6, 6, 6, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6, 6,
30  6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 4, 6, 4, 6, 6,
31  6, 6, 6, 6, 6, 5, 6, 6, 2, 6, 5, 3, 6, 6, 6, 6,
32  6, 6, 6, 4, 6, 6, 6, 6, 6, 6, 5, 2, 5, 7
33  ];
34 
35  const CHAT_WINDOW_WIDTH = 240;
36  const CHAT_STRING_LENGTH = 119;
37 
38  private static $allowedChars = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz{|}~";
39 
40  private static $allowedCharsArray = [];
41 
42  public static function init(){
43  self::$allowedCharsArray = [];
44  $len = strlen(self::$allowedChars);
45  for($i = 0; $i < $len; ++$i){
46  self::$allowedCharsArray[self::$allowedChars{$i}] = self::$characterWidths[$i];
47  }
48  }
49 
50  public static function wrap($text){
51  $result = "";
52  $len = strlen($text);
53  $lineWidth = 0;
54  $lineLength = 0;
55 
56  for($i = 0; $i < $len; ++$i){
57  $char = $text{$i};
58 
59  if($char === "\n"){
60  $lineLength = 0;
61  $lineWidth = 0;
62  }elseif(isset(self::$allowedCharsArray[$char])){
63  $width = self::$allowedCharsArray[$char];
64 
65  if($lineLength + 1 > self::CHAT_STRING_LENGTH or $lineWidth + $width > self::CHAT_WINDOW_WIDTH){
66  $result .= "\n";
67  $lineLength = 0;
68  $lineWidth = 0;
69  }
70 
71  ++$lineLength;
72  $lineWidth += $width;
73  }else{
74  return $text;
75  }
76 
77  $result .= $char;
78  }
79 
80  return $result;
81  }
82 }