├── php
├── testdata
│ └── test_fpc.txt
├── print.go
├── echo.go
├── exec.go
├── time.go
├── array_push.go
├── print_r.go
├── basename.go
├── sys_get_temp_dir.go
├── file_get_contents.go
├── doc.go
├── is_file.go
├── exit.go
├── scandir.go
├── random_bytes.go
├── array_merge.go
├── date_add.go
├── array.go
├── array_reverse.go
├── sleep.go
├── array_fill_keys.go
├── array_flip.go
├── array_fill.go
├── directory.go
├── addcslashes.go
├── array_count_values.go
├── array_column.go
├── addslashes.go
├── json.go
├── array_keys.go
├── file_put_contents.go
├── base64.go
├── array_intersect.go
├── chunk_split.go
├── md5.go
├── sha1.go
├── array_chunk.go
├── array_change_key_case.go
├── url.go
├── checkdate.go
├── number_format.go
├── is_numeric.go
├── date.go
├── variable.go
├── filesystem.go
├── math.go
└── strings.go
├── go.mod
├── .gitignore
├── main.go
├── LICENSE
└── README.md
/php/testdata/test_fpc.txt:
--------------------------------------------------------------------------------
1 | this is a test string
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/awesee/php2go
2 |
3 | go 1.16
4 |
--------------------------------------------------------------------------------
/php/print.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // Print - Output a string
4 | func Print(v interface{}) {
5 |
6 | print(v)
7 | }
8 |
--------------------------------------------------------------------------------
/php/echo.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "fmt"
4 |
5 | // Echo - Output one or more strings
6 | func Echo(args ...interface{}) {
7 |
8 | fmt.Print(args...)
9 | }
10 |
--------------------------------------------------------------------------------
/php/exec.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "os/exec"
4 |
5 | // Exec - Execute an external program
6 | func Exec(s string) {
7 |
8 | exec.Command(s).Run()
9 | }
10 |
--------------------------------------------------------------------------------
/php/time.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "time"
4 |
5 | // Time - Return current Unix timestamp
6 | func Time() int64 {
7 |
8 | return time.Now().Unix()
9 | }
10 |
--------------------------------------------------------------------------------
/php/array_push.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // ArrayPush - Push one or more elements onto the end of array
4 | func ArrayPush(s *[]string, args ...string) {
5 |
6 | *s = append(*s, args...)
7 | }
8 |
--------------------------------------------------------------------------------
/php/print_r.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "fmt"
4 |
5 | // PrintR - Prints human-readable information about a variable
6 | func PrintR(v interface{}) {
7 |
8 | fmt.Print(v)
9 | }
10 |
--------------------------------------------------------------------------------
/php/basename.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "path/filepath"
4 |
5 | // Basename - Returns trailing name component of path
6 | func Basename(path string) string {
7 | return filepath.Base(path)
8 | }
9 |
--------------------------------------------------------------------------------
/php/sys_get_temp_dir.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "os"
4 |
5 | // SysGetTempDir - Returns directory path used for temporary files
6 | func SysGetTempDir() string {
7 |
8 | return os.TempDir()
9 | }
10 |
--------------------------------------------------------------------------------
/php/file_get_contents.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "io/ioutil"
4 |
5 | // FileGetContents - Reads entire file into a string
6 | func FileGetContents(filename string) ([]byte, error) {
7 | return ioutil.ReadFile(filename)
8 | }
9 |
--------------------------------------------------------------------------------
/php/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Awesee. All rights reserved.
2 | // Use of this source code is governed by a MIT
3 | // license that can be found in the LICENSE file.
4 |
5 | // PHP built-in function library with Go language
6 | package php
7 |
--------------------------------------------------------------------------------
/php/is_file.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "os"
4 |
5 | // IsFile Tells whether the filename is a regular file
6 | func IsFile(name string) bool {
7 |
8 | fi, err := os.Stat(name)
9 |
10 | return err == nil && fi.Mode().IsRegular()
11 | }
12 |
13 |
--------------------------------------------------------------------------------
/php/exit.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "os"
4 |
5 | // Exit — Output a message and terminate the current script
6 | func Exit(code int) {
7 | os.Exit(code)
8 | }
9 |
10 | // Die — Equivalent to exit
11 | func Die(code int) {
12 | Exit(code)
13 | }
14 |
--------------------------------------------------------------------------------
/php/scandir.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import (
4 | "io/ioutil"
5 | "os"
6 | )
7 |
8 | // scandir — List files and directories inside the specified path
9 | func Scandir(dirname string) ([]os.FileInfo, error) {
10 | return ioutil.ReadDir(dirname)
11 | }
12 |
--------------------------------------------------------------------------------
/php/random_bytes.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "crypto/rand"
4 |
5 | // RandomBytes — Generates cryptographically secure pseudo-random bytes
6 | func RandomBytes(len int) []byte {
7 | b := make([]byte, len)
8 | _, _ = rand.Read(b)
9 | return b
10 | }
11 |
--------------------------------------------------------------------------------
/php/array_merge.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // ArrayMerge — Merge one or more arrays
4 | func ArrayMerge(arr ...[]interface{}) []interface{} {
5 |
6 | s := make([]interface{}, 0)
7 | for _, v := range arr {
8 | s = append(s, v...)
9 | }
10 |
11 | return s
12 | }
13 |
--------------------------------------------------------------------------------
/php/date_add.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "time"
4 |
5 | // DateAdd - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
6 | func DateAdd(t time.Time, years int, months int, days int) time.Time {
7 | return t.AddDate(years, months, days)
8 | }
9 |
--------------------------------------------------------------------------------
/php/array.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // Array - Create an array
4 | func Array(v ...interface{}) []interface{} {
5 |
6 | return v
7 | }
8 |
9 | // Count - Count all elements in an array, or something in an object
10 | func Count(v []interface{}) int {
11 |
12 | return len(v)
13 | }
14 |
--------------------------------------------------------------------------------
/php/array_reverse.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // ArrayReverse - Return an array with elements in reverse order
4 | func ArrayReverse(s []interface{}) []interface{} {
5 |
6 | for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
7 | s[i], s[j] = s[j], s[i]
8 | }
9 |
10 | return s
11 | }
12 |
--------------------------------------------------------------------------------
/php/sleep.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "time"
4 |
5 | // Sleep - Delay execution
6 | func Sleep(s int64) {
7 | time.Sleep(time.Duration(s) * time.Second)
8 | }
9 |
10 | // Usleep - Delay execution in microseconds
11 | func Usleep(ms int64) {
12 | time.Sleep(time.Duration(ms) * time.Microsecond)
13 | }
14 |
--------------------------------------------------------------------------------
/php/array_fill_keys.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // ArrayFillKeys - Fill an array with values, specifying keys
4 | func ArrayFillKeys(keys []interface{}, value interface{}) map[interface{}]interface{} {
5 |
6 | r := make(map[interface{}]interface{})
7 | for _, v := range keys {
8 | r[v] = value
9 | }
10 |
11 | return r
12 | }
13 |
--------------------------------------------------------------------------------
/php/array_flip.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // ArrayFlip - Exchanges all keys with their associated values in an array
4 | func ArrayFlip(arrayMap map[interface{}]interface{}) map[interface{}]interface{} {
5 |
6 | r := make(map[interface{}]interface{})
7 | for i, v := range arrayMap {
8 | r[v] = i
9 | }
10 |
11 | return r
12 | }
13 |
--------------------------------------------------------------------------------
/php/array_fill.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // ArrayFill - Fill an array with values
4 | func ArrayFill(startIndex uint, num uint, value interface{}) map[uint]interface{} {
5 |
6 | r := make(map[uint]interface{})
7 | var i uint
8 | for i = 0; i < num; i++ {
9 | r[startIndex] = value
10 | startIndex++
11 | }
12 |
13 | return r
14 | }
15 |
--------------------------------------------------------------------------------
/php/directory.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "os"
4 |
5 | // Chdir - Change directory
6 | func Chdir(dir string) error {
7 |
8 | return os.Chdir(dir)
9 | }
10 |
11 | // Getcwd - Get current directory
12 | func Getcwd() (dir string) {
13 |
14 | dir, err := os.Getwd()
15 | if err != nil {
16 | dir = err.Error()
17 | }
18 | return
19 | }
20 |
--------------------------------------------------------------------------------
/php/addcslashes.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // Addcslashes - Quote string with slashes in a C style
4 | func Addcslashes(s string, c byte) string {
5 |
6 | l := len(s)
7 | r := make([]byte, l, l*2)
8 | for i := 0; i < l; i++ {
9 | if s[i] == c {
10 | r = append(r, '\\')
11 | }
12 |
13 | r = append(r, s[i])
14 | }
15 |
16 | return string(r)
17 | }
18 |
--------------------------------------------------------------------------------
/php/array_count_values.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // ArrayCountValues — Counts all the values of an array
4 | func ArrayCountValues(s []interface{}) map[interface{}]uint {
5 |
6 | r := make(map[interface{}]uint)
7 | for _, v := range s {
8 | if c, ok := r[v]; ok {
9 | r[v] = c + 1
10 | } else {
11 | r[v] = 1
12 | }
13 | }
14 |
15 | return r
16 | }
17 |
--------------------------------------------------------------------------------
/php/array_column.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // ArrayColumn — Return the values from a single column in the input array
4 | func ArrayColumn(arrayMap map[string]map[string]interface{}, columnKey string) (r []interface{}) {
5 |
6 | for _, input := range arrayMap {
7 | if v, ok := input[columnKey]; ok {
8 | r = append(r, v)
9 | }
10 | }
11 |
12 | return
13 | }
14 |
--------------------------------------------------------------------------------
/php/addslashes.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // Addslashes - Quote string with slashes
4 | func Addslashes(s string) string {
5 |
6 | l := len(s)
7 | r := make([]byte, l, l*2)
8 | for i := 0; i < l; i++ {
9 |
10 | switch s[i] {
11 | case '\'', '"', '\\':
12 | r = append(r, '\\')
13 | }
14 |
15 | r = append(r, s[i])
16 | }
17 |
18 | return string(r)
19 | }
20 |
--------------------------------------------------------------------------------
/php/json.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import (
4 | "encoding/json"
5 | )
6 |
7 | // JsonEncode - Returns the JSON representation of a value
8 | func JsonEncode(v interface{}) ([]byte, error) {
9 |
10 | return json.Marshal(v)
11 | }
12 |
13 | // JsonDecode - Decodes a JSON string
14 | func JsonDecode(data []byte, v interface{}) error {
15 |
16 | return json.Unmarshal(data, v)
17 | }
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Binaries for programs and plugins
2 | *.exe
3 | *.dll
4 | *.so
5 | *.dylib
6 |
7 | # Test binary, build with `go test -c`
8 | *.test
9 |
10 | # Output of the go coverage tool, specifically when used with LiteIDE
11 | *.out
12 |
13 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
14 | .glide/
15 |
16 | .DS_Store
17 | .idea/
18 |
19 | vendor/
20 |
--------------------------------------------------------------------------------
/php/array_keys.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // ArrayKeys - get keys of map data as a Array
4 | // in php,the keys you want always is string or number
5 | // here,let it be string
6 | func ArrayKeys(data map[string]interface{}) []string {
7 | if len(data) < 1 {
8 | return []string{}
9 | }
10 | var resData []string
11 | for index := range data {
12 | resData = append(resData, index)
13 | }
14 | return resData
15 | }
16 |
--------------------------------------------------------------------------------
/php/file_put_contents.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import (
4 | "io/ioutil"
5 | "os"
6 | "path/filepath"
7 | )
8 |
9 | // FilePutContents - Write data to a file
10 | func FilePutContents(filename string, data []byte) error {
11 | if dir := filepath.Dir(filename); dir != "" {
12 | if err := os.MkdirAll(dir, 0755); err != nil {
13 | return err
14 | }
15 | }
16 | return ioutil.WriteFile(filename, data, 0644)
17 | }
18 |
--------------------------------------------------------------------------------
/php/base64.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "encoding/base64"
4 |
5 | // Base64Encode - Encodes data with MIME base64
6 | func Base64Encode(s string) string {
7 | return base64.StdEncoding.EncodeToString([]byte(s))
8 | }
9 |
10 | // Base64Decode - Decodes data encoded with MIME base64
11 | func Base64Decode(s string) (string, error) {
12 | bs, err := base64.StdEncoding.DecodeString(s)
13 | return string(bs), err
14 | }
15 |
--------------------------------------------------------------------------------
/php/array_intersect.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // ArrayIntersect — Computes the intersection of arrays
4 | func ArrayIntersect(nums1, nums2 []int) []int {
5 |
6 | res := make([]int, 0, len(nums1))
7 | nc := make(map[int]int)
8 |
9 | for _, n := range nums1 {
10 | nc[n]++
11 | }
12 |
13 | for _, n := range nums2 {
14 | if nc[n] > 0 {
15 | res = append(res, n)
16 | nc[n]--
17 | }
18 | }
19 |
20 | return res
21 | }
22 |
--------------------------------------------------------------------------------
/php/chunk_split.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "bytes"
4 |
5 | // ChunkSplit - Split a string into smaller chunks
6 | func ChunkSplit(str string, chunkLen int, end string) string {
7 | if chunkLen <= 0 {
8 | return str
9 | }
10 | var buf bytes.Buffer
11 | l := len(str)
12 | for i := 0; i < l; i += chunkLen {
13 | if chunkLen > l-i {
14 | chunkLen = l - i
15 | }
16 | buf.WriteString(str[i : i+chunkLen])
17 | buf.WriteString(end)
18 | }
19 | return buf.String()
20 | }
21 |
--------------------------------------------------------------------------------
/php/md5.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import (
4 | "crypto/md5"
5 | "encoding/hex"
6 | "io/ioutil"
7 | )
8 |
9 | // Md5 - Calculate the md5 hash of a string
10 | func Md5(s string) string {
11 | hash := md5.Sum([]byte(s))
12 | return hex.EncodeToString(hash[:])
13 | }
14 |
15 | // Md5File - Calculates the md5 hash of a given file
16 | func Md5File(filename string) string {
17 | data, err := ioutil.ReadFile(filename)
18 | if err != nil {
19 | return ""
20 | }
21 | hash := md5.Sum(data)
22 | return hex.EncodeToString(hash[:])
23 | }
24 |
--------------------------------------------------------------------------------
/php/sha1.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import (
4 | "crypto/sha1"
5 | "encoding/hex"
6 | "io/ioutil"
7 | )
8 |
9 | // Sha1 - Calculate the sha1 hash of a string
10 | func Sha1(s string) string {
11 | digest := sha1.Sum([]byte(s))
12 | return hex.EncodeToString(digest[:])
13 | }
14 |
15 | // Sha1File - Calculates the md5 hash of a given file
16 | func Sha1File(filename string) string {
17 | data, err := ioutil.ReadFile(filename)
18 | if err != nil {
19 | return ""
20 | }
21 | digest := sha1.Sum(data)
22 | return hex.EncodeToString(digest[:])
23 | }
24 |
--------------------------------------------------------------------------------
/php/array_chunk.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | )
7 |
8 | // ArraySlice type
9 | type ArraySlice []interface{}
10 |
11 | // ArrayChunk - Split an array into chunks
12 | func ArrayChunk(input ArraySlice, size int) ArraySlice {
13 |
14 | length := len(input)
15 | count := int(math.Ceil(float64(length) / float64(size)))
16 | ret := make(ArraySlice, count)
17 | for i := 0; i < count-1; i++ {
18 | ret[i] = input[i*size : (i+1)*size]
19 | fmt.Println(ret)
20 | }
21 | ret[count-1] = input[size*(count-1):]
22 |
23 | return ret
24 | }
25 |
--------------------------------------------------------------------------------
/php/array_change_key_case.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import "strings"
4 |
5 | // ArrayMap is one of Array type
6 | type ArrayMap map[string]interface{}
7 |
8 | // Constants for ArrayChangeKeyCase
9 | const (
10 | CaseLOWER = iota
11 | CaseUPPER
12 | )
13 |
14 | // ArrayChangeKeyCase - Changes the case of all keys in an array
15 | func ArrayChangeKeyCase(arr ArrayMap, Case int) ArrayMap {
16 |
17 | var tmp = ArrayMap{}
18 | for k, v := range arr {
19 | if Case == CaseUPPER {
20 | tmp[strings.ToUpper(k)] = v
21 | } else if Case == CaseLOWER {
22 | tmp[strings.ToLower(k)] = v
23 | }
24 | }
25 |
26 | return tmp
27 | }
28 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/awesee/php2go/php"
7 | )
8 |
9 | func main() {
10 |
11 | php.Echo("Hello ", "world!\n")
12 |
13 | php.Print("This is a string.\n")
14 |
15 | fmt.Println(php.Chr(65))
16 |
17 | fmt.Println(php.Ord('A'))
18 |
19 | fmt.Println(php.Array(1, 'a', "ABC"))
20 |
21 | fmt.Println(php.Strrev("Hello world!"))
22 |
23 | fmt.Println(php.Strrev("你好,世界"))
24 |
25 | fmt.Println(php.ArrayReverse(php.Array(1, 'a', "ABC")))
26 |
27 | fmt.Println(php.SysGetTempDir())
28 |
29 | fmt.Println(php.IsNumeric("-123.45"))
30 |
31 | fmt.Println(php.Basename("foo/bar.ext"))
32 |
33 | fmt.Println(php.Addcslashes("abc/cde.ext", 'c'))
34 |
35 | fmt.Println(php.Addslashes("abc/'\"c\\de.ext"))
36 |
37 | fmt.Println(php.Htmlspecialchars("This is some bold text."))
38 |
39 | fmt.Println(php.MbStrlen("你好,世界"))
40 |
41 | fmt.Println(php.Intval("-123abc"))
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/php/url.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import (
4 | "net/url"
5 | )
6 |
7 | // ParseUrl - Parse a URL and return its components
8 | func ParseUrl(rawurl string) (*url.URL, error) {
9 |
10 | return url.Parse(rawurl)
11 | }
12 |
13 | // ParseStr - Parses the string into variables
14 | func ParseStr(query string) (url.Values, error) {
15 |
16 | return url.ParseQuery(query)
17 | }
18 |
19 | // Rawurlencode - URL-encode according to RFC 3986
20 | func Rawurlencode(s string) string {
21 |
22 | return url.PathEscape(s)
23 | }
24 |
25 | // Rawurldecode - Decodes URL-encoded string
26 | func Rawurldecode(s string) (string, error) {
27 |
28 | return url.PathUnescape(s)
29 | }
30 |
31 | // Urlencode - URL-encodes string
32 | func Urlencode(s string) string {
33 |
34 | return url.QueryEscape(s)
35 | }
36 |
37 | // Urldecode - Decodes URL-encoded string
38 | func Urldecode(s string) (string, error) {
39 |
40 | return url.QueryUnescape(s)
41 | }
42 |
--------------------------------------------------------------------------------
/php/checkdate.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // Checkdate - Validate a Gregorian date
4 | func Checkdate(month, day, year uint) bool {
5 |
6 | //check month
7 | switch month {
8 | case 1, 3, 5, 7, 8, 10, 12:
9 | if day > 31 {
10 | return false
11 | }
12 | case 4, 6, 9, 11:
13 | if day > 30 {
14 | return false
15 | }
16 | case 2:
17 | if checkIfLeapYear(year) {
18 | if day > 29 {
19 | return false
20 | }
21 | } else {
22 | if day > 28 {
23 | return false
24 | }
25 | }
26 | default:
27 | return false
28 | }
29 |
30 | //check day
31 | if day < 1 {
32 | return false
33 | }
34 |
35 | //check year
36 | if year < 1 || year > 32767 {
37 | return false
38 | }
39 |
40 | return true
41 | }
42 |
43 | func checkIfLeapYear(year uint) bool {
44 |
45 | if year%100 == 0 {
46 | if year%400 == 0 {
47 | return true
48 | }
49 | return false
50 | }
51 | if year%4 == 0 {
52 | return true
53 | }
54 |
55 | return false
56 | }
57 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Awesee
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/php/number_format.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import (
4 | "fmt"
5 | "strconv"
6 | )
7 |
8 | // NumberFormat — Format a number with grouped thousands
9 | func NumberFormat(number float64, decimals uint, decPoint, thousandsSep string) string {
10 | neg := false
11 | if number < 0 {
12 | number = -number
13 | neg = true
14 | }
15 | dec := int(decimals)
16 | // Will round off
17 | str := fmt.Sprintf("%."+strconv.Itoa(dec)+"F", number)
18 | prefix, suffix := "", ""
19 | if dec > 0 {
20 | prefix = str[:len(str)-(dec+1)]
21 | suffix = str[len(str)-dec:]
22 | } else {
23 | prefix = str
24 | }
25 | sep := []byte(thousandsSep)
26 | n, l1, l2 := 0, len(prefix), len(sep)
27 | // thousands sep num
28 | c := (l1 - 1) / 3
29 | tmp := make([]byte, l2*c+l1)
30 | pos := len(tmp) - 1
31 | for i := l1 - 1; i >= 0; i, n, pos = i-1, n+1, pos-1 {
32 | if l2 > 0 && n > 0 && n%3 == 0 {
33 | for j := range sep {
34 | tmp[pos] = sep[l2-j-1]
35 | pos--
36 | }
37 | }
38 | tmp[pos] = prefix[i]
39 | }
40 | s := string(tmp)
41 | if dec > 0 {
42 | s += decPoint + suffix
43 | }
44 | if neg {
45 | s = "-" + s
46 | }
47 | return s
48 | }
49 |
--------------------------------------------------------------------------------
/php/is_numeric.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // IsNumeric - Finds whether a variable is a number or a numeric string
4 | func IsNumeric(x interface{}) (result bool) {
5 |
6 | //Figure out result
7 | switch x.(type) {
8 |
9 | case int, uint:
10 | result = true
11 | case int8, uint8:
12 | result = true
13 | case int16, uint16:
14 | result = true
15 | case int32, uint32:
16 | result = true
17 | case int64, uint64:
18 | result = true
19 |
20 | case float32, float64:
21 | result = true
22 |
23 | case complex64, complex128:
24 | result = true
25 |
26 | case string:
27 | if xAsString, ok := x.(string); ok {
28 | result = isStringNumeric(xAsString)
29 | } else {
30 | result = false
31 | }
32 |
33 | default:
34 | result = false
35 |
36 | }
37 |
38 | return result
39 | }
40 |
41 | func isStringNumeric(x string) bool {
42 |
43 | hasPeriod := false
44 | for i, c := range x {
45 | println(i)
46 | switch c {
47 |
48 | case '-':
49 | if i != 0 {
50 | return false
51 | }
52 |
53 | case '.':
54 | if hasPeriod {
55 | return false
56 | }
57 | hasPeriod = true
58 |
59 | case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
60 | //Nothing here.
61 |
62 | default:
63 | return false
64 |
65 | }
66 | }
67 |
68 | return true
69 | }
70 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## [用Go语言实现PHP内置函数](https://awesee.github.io/php2go)
2 |
3 | [](https://travis-ci.org/awesee/php2go)
4 | [](https://goreportcard.com/report/github.com/awesee/php2go)
5 | [](https://godoc.org/github.com/awesee/php2go/php)
6 | [](https://github.com/awesee/php2go/graphs/contributors)
7 | [](https://github.com/awesee/php2go/blob/master/LICENSE)
8 | [](https://github.com/awesee/php2go/archive/master.zip)
9 |
10 | 这是一个用Go语言开发的辅助库,尤其适用于熟悉PHP内置函数的开发者,将会实现PHP内置函数。
11 |
12 | ### 下载安装
13 |
14 | ```shell
15 |
16 | go get -u github.com/awesee/php2go/php
17 |
18 | ```
19 |
20 | ### 关于命名
21 |
22 | PHP下划线命名转为Go大驼峰命名。
23 |
24 | ### Example:
25 |
26 | ```go
27 |
28 | package main
29 |
30 | import (
31 | "github.com/awesee/php2go/php"
32 | )
33 |
34 | func main() {
35 |
36 | php.Echo("Hello ", "world!\n")
37 |
38 | }
39 |
40 | ```
41 |
42 | [More](https://github.com/awesee/php2go/blob/master/main.go)
43 |
44 | ### 项目进度
45 |
46 | [TODO List](https://github.com/awesee/php2go/blob/master/TODO.md)
47 |
48 | ### 贡献代码
49 |
50 | [贡献指南](https://github.com/awesee/php2go/blob/master/.github/CONTRIBUTING.md)
51 |
52 | ## Contributors
53 |
54 | [Your contributions are always welcome!](https://github.com/awesee/php2go/graphs/contributors)
55 |
56 | ## LICENSE
57 |
58 | Released under [MIT](https://github.com/awesee/php2go/blob/master/LICENSE) LICENSE
59 |
--------------------------------------------------------------------------------
/php/date.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | // Date takes a PHP like date func to Go's time fomate
4 | import (
5 | "strings"
6 | "time"
7 | )
8 |
9 | // DateFormat pattern rules.
10 | var datePatterns = []string{
11 | // year
12 | "Y", "2006", // A full numeric representation of a year, 4 digits Examples: 1999 or 2003
13 | "y", "06", // A two digit representation of a year Examples: 99 or 03
14 |
15 | // month
16 | "m", "01", // Numeric representation of a month, with leading zeros 01 through 12
17 | "n", "1", // Numeric representation of a month, without leading zeros 1 through 12
18 | "M", "Jan", // A short textual representation of a month, three letters Jan through Dec
19 | "F", "January", // A full textual representation of a month, such as January or March January through December
20 |
21 | // day
22 | "d", "02", // Day of the month, 2 digits with leading zeros 01 to 31
23 | "j", "2", // Day of the month without leading zeros 1 to 31
24 |
25 | // week
26 | "D", "Mon", // A textual representation of a day, three letters Mon through Sun
27 | "l", "Monday", // A full textual representation of the day of the week Sunday through Saturday
28 |
29 | // time
30 | "g", "3", // 12-hour format of an hour without leading zeros 1 through 12
31 | "G", "15", // 24-hour format of an hour without leading zeros 0 through 23
32 | "h", "03", // 12-hour format of an hour with leading zeros 01 through 12
33 | "H", "15", // 24-hour format of an hour with leading zeros 00 through 23
34 |
35 | "a", "pm", // Lowercase Ante meridiem and Post meridiem am or pm
36 | "A", "PM", // Uppercase Ante meridiem and Post meridiem AM or PM
37 |
38 | "i", "04", // Minutes with leading zeros 00 to 59
39 | "s", "05", // Seconds, with leading zeros 00 through 59
40 |
41 | // time zone
42 | "T", "MST",
43 | "P", "-07:00",
44 | "O", "-0700",
45 |
46 | // RFC 2822
47 | "r", time.RFC1123Z,
48 | }
49 |
50 | // Date - Format a local time/date
51 | func Date(format string, ts ...time.Time) string {
52 | replacer := strings.NewReplacer(datePatterns...)
53 | format = replacer.Replace(format)
54 | t := time.Now()
55 | if len(ts) > 0 {
56 | t = ts[0]
57 | }
58 | return t.Format(format)
59 | }
60 |
--------------------------------------------------------------------------------
/php/variable.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import (
4 | "fmt"
5 | "reflect"
6 | "strconv"
7 | "strings"
8 | "unicode"
9 | )
10 |
11 | // Boolval - Get the boolean value of a variable
12 | func Boolval(val interface{}) bool {
13 |
14 | switch v := val.(type) {
15 | case int, int8, int16, int32, int64:
16 | if v != 0 {
17 | return true
18 | }
19 | return false
20 | case uint, uint8, uint16, uint32, uint64:
21 | if v != 0 {
22 | return true
23 | }
24 | return false
25 | case bool:
26 | return v
27 | case complex64, complex128:
28 | if v != complex128(0) {
29 | return true
30 | }
31 | return false
32 | case float32, float64:
33 | if v != float64(0) {
34 | return true
35 | }
36 | default:
37 | return v == nil
38 | }
39 |
40 | return false
41 | }
42 |
43 | // Empty - Determine whether a variable is empty
44 | func Empty(v interface{}) bool {
45 |
46 | if v == nil {
47 | return true
48 | }
49 |
50 | val := reflect.ValueOf(v)
51 | switch val.Kind() {
52 | case reflect.Bool:
53 | return !val.Bool()
54 |
55 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
56 | return val.Int() == 0
57 |
58 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
59 | return val.Uint() == 0
60 |
61 | case reflect.Float32, reflect.Float64:
62 | return val.Float() == 0.00
63 |
64 | case reflect.Complex64, reflect.Complex128:
65 | return val.Complex() == 0+0i
66 |
67 | case reflect.String:
68 | realVal := val.String()
69 | return realVal == "" || realVal == "0"
70 |
71 | case reflect.Array, reflect.Slice, reflect.Map, reflect.Chan:
72 | return val.Len() == 0
73 |
74 | case reflect.Struct:
75 | return val.NumField() == 0
76 | }
77 |
78 | return false
79 | }
80 |
81 | // Intval - Get the integer value of a variable
82 | func Intval(str string) (int, error) {
83 |
84 | str = strings.TrimSpace(str)
85 | pre := ""
86 | if strings.HasPrefix(str, "-") || strings.HasPrefix(str, "+") {
87 | pre = str[0:1]
88 | str = str[1:]
89 | }
90 |
91 | i := strings.IndexFunc(str, func(r rune) bool {
92 | return !unicode.IsNumber(r)
93 | })
94 | if i > -1 {
95 | str = str[0:i]
96 | }
97 | if str == "" {
98 | str = "0"
99 | }
100 |
101 | return strconv.Atoi(pre + str)
102 | }
103 |
104 | // Strval - Get string value of a variable
105 | func Strval(val interface{}) string {
106 |
107 | return fmt.Sprintf("%v", val)
108 | }
109 |
110 | // Gettype - Get the type of a variable
111 | func Gettype(v interface{}) string {
112 |
113 | // t := reflect.TypeOf(v)
114 | //
115 | // return t.String()
116 | return fmt.Sprintf("%T", v)
117 | }
118 |
119 | // IsBool - Finds out whether a variable is a boolean
120 | func IsBool(v interface{}) bool {
121 |
122 | // _, ok := v.(bool)
123 | //
124 | // return ok
125 | return v == true || v == false
126 | }
127 |
--------------------------------------------------------------------------------
/php/filesystem.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import (
4 | "io"
5 | "io/ioutil"
6 | "os"
7 | "path/filepath"
8 | "syscall"
9 | "time"
10 | )
11 |
12 | // Chgrp - Changes file group
13 | func Chgrp(name string, uid, gid int) error {
14 | return Chown(name, uid, gid)
15 | }
16 |
17 | // Chmod - Changes file mode
18 | func Chmod(name string, mode os.FileMode) error {
19 | return os.Chmod(name, mode)
20 | }
21 |
22 | // Chown - Chown changes the numeric uid and gid of the named file.
23 | func Chown(name string, uid int, gid int) error {
24 | return os.Chown(name, uid, gid)
25 | }
26 |
27 | // Copy - Copies file
28 | func Copy(dstName string, srcName string) (written int64, err error) {
29 | src, err := os.Open(srcName)
30 | if err != nil {
31 | return
32 | }
33 | defer src.Close()
34 | dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
35 | if err != nil {
36 | return
37 | }
38 | defer dst.Close()
39 | return io.Copy(dst, src)
40 | }
41 |
42 | // Delete - Deletes a file
43 | func Delete(name string) error {
44 | return Unlink(name)
45 | }
46 |
47 | // Dirname - Returns a parent directory's path
48 | func Dirname(dirPth string) ([]os.FileInfo, error) {
49 | return ioutil.ReadDir(dirPth)
50 | }
51 |
52 | // Fclose - Closes an open file pointer
53 | func Fclose(file *os.File) error {
54 | return file.Close()
55 | }
56 |
57 | // FileExists - Checks whether a file or directory exists
58 | func FileExists(path string) bool {
59 | _, err := os.Stat(path)
60 | return err == nil
61 | }
62 |
63 | // Filemtime - Gets file modification time
64 | func Filemtime(file string) time.Time {
65 | fi, err := os.Stat(file)
66 | if err != nil {
67 | return time.Time{}
68 | }
69 | return fi.ModTime()
70 | }
71 |
72 | // Glob - Find pathnames matching a pattern
73 | func Glob(pattern string) (matches []string, err error) {
74 | return filepath.Glob(pattern)
75 | }
76 |
77 | // IsDir - Tells whether the filename is a directory
78 | func IsDir(name string) bool {
79 | fi, err := os.Stat(name)
80 | return err == nil && fi.IsDir()
81 | }
82 |
83 | // IsReadable - Tells whether a file exists and is readable
84 | func IsReadable(name string) bool {
85 | _, err := syscall.Open(name, syscall.O_RDONLY, 0)
86 | return err == nil
87 | }
88 |
89 | // IsWritable - Tells whether the filename is writable
90 | func IsWritable(name string) bool {
91 | _, err := syscall.Open(name, syscall.O_WRONLY, 0)
92 | return err == nil
93 | }
94 |
95 | // IsWriteable - Alias of IsWritable()
96 | func IsWriteable(name string) bool {
97 | return IsWritable(name)
98 | }
99 |
100 | // Mkdir - Makes directory
101 | func Mkdir(name string, mode os.FileMode) error {
102 | return os.Mkdir(name, mode)
103 | }
104 |
105 | // Realpath - Returns canonicalized absolute pathname
106 | func Realpath(path string) (string, error) {
107 | return filepath.Abs(path)
108 | }
109 |
110 | // Rename - Renames a file or directory
111 | func Rename(oldpath, newpath string) error {
112 | return os.Rename(oldpath, newpath)
113 | }
114 |
115 | // Rmdir — Removes directory
116 | func Rmdir(path string) error {
117 | return os.RemoveAll(path)
118 | }
119 |
120 | // Stat - Gives information about a file
121 | func Stat(name string) (os.FileInfo, error) {
122 | return os.Stat(name)
123 | }
124 |
125 | // Unlink - Deletes a file
126 | func Unlink(name string) error {
127 | return os.Remove(name)
128 | }
129 |
--------------------------------------------------------------------------------
/php/math.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import (
4 | "math"
5 | "math/cmplx"
6 | "math/rand"
7 | "strconv"
8 | "time"
9 | )
10 |
11 | // Abs - Absolute xue
12 | func Abs(x float64) float64 {
13 | return math.Abs(x)
14 | }
15 |
16 | // Acos - Arc cosine
17 | func Acos(x complex128) complex128 {
18 | return cmplx.Acos(x)
19 | }
20 |
21 | // Acosh - Inverse hyperbolic cosine
22 | func Acosh(x complex128) complex128 {
23 | return cmplx.Acosh(x)
24 | }
25 |
26 | // Asin - Arc sine
27 | func Asin(x complex128) complex128 {
28 | return cmplx.Asin(x)
29 | }
30 |
31 | // Asinh - Inverse hyperbolic sine
32 | func Asinh(x complex128) complex128 {
33 | return cmplx.Asinh(x)
34 | }
35 |
36 | // Atan2 - Arc tangent of two variables
37 | func Atan2(y, x float64) float64 {
38 | return math.Atan2(y, x)
39 | }
40 |
41 | // Atan - Arc tangent
42 | func Atan(x complex128) complex128 {
43 | return cmplx.Atan(x)
44 | }
45 |
46 | // Atanh - Inverse hyperbolic tangent
47 | func Atanh(x complex128) complex128 {
48 | return cmplx.Atanh(x)
49 | }
50 |
51 | // BaseConvert - Convert a number between arbitrary bases
52 | func BaseConvert(num string, frombase, tobase int) (string, error) {
53 | i, err := strconv.ParseInt(num, frombase, 0)
54 | if err != nil {
55 | return "", err
56 | }
57 | return strconv.FormatInt(i, tobase), nil
58 | }
59 |
60 | // Ceil - Round fractions up
61 | func Ceil(x float64) float64 {
62 | return math.Ceil(x)
63 | }
64 |
65 | // Cos - Cosine
66 | func Cos(x float64) float64 {
67 | return math.Cos(x)
68 | }
69 |
70 | // Cosh - Hyperbolic cosine
71 | func Cosh(x float64) float64 {
72 | return math.Cosh(x)
73 | }
74 |
75 | // Decbin - Decimal to binary
76 | func Decbin(x int64) string {
77 | return strconv.FormatInt(x, 2)
78 | }
79 |
80 | // Dechex - Decimal to hexadecimal
81 | func Dechex(x int64) string {
82 | return strconv.FormatInt(x, 16)
83 | }
84 |
85 | // Decoct - Decimal to octal
86 | func Decoct(x int64) string {
87 | return strconv.FormatInt(x, 8)
88 | }
89 |
90 | // Exp - Calculates the exponent of e
91 | func Exp(x float64) float64 {
92 | return math.Exp(x)
93 | }
94 |
95 | // Expm1 - Returns exp(number) - 1
96 | // computed in a way that is accurate even when the value of number is close to zero
97 | func Expm1(x float64) float64 {
98 | return math.Exp(x) - 1
99 | }
100 |
101 | // Floor - Round fractions down
102 | func Floor(x float64) float64 {
103 | return math.Floor(x)
104 | }
105 |
106 | // IsFinite - Finds whether a value is a legal finite number
107 | func IsFinite(f float64, sign int) bool {
108 | return !math.IsInf(f, sign)
109 | }
110 |
111 | // IsInfinite - Finds whether a value is infinite
112 | func IsInfinite(f float64, sign int) bool {
113 | return math.IsInf(f, sign)
114 | }
115 |
116 | // IsNan - Finds whether a value is not a number
117 | func IsNan(f float64) bool {
118 | return math.IsNaN(f)
119 | }
120 |
121 | // Log - Natural logarithm
122 | func Log(x float64) float64 {
123 | return math.Log(x)
124 | }
125 |
126 | // Log10 - Base-10 logarithm
127 | func Log10(x float64) float64 {
128 | return math.Log10(x)
129 | }
130 |
131 | // Log1p - Returns log(1 + number)
132 | // computed in a way that is accurate even when the value of number is close to zero
133 | func Log1p(x float64) float64 {
134 | return math.Log1p(x)
135 | }
136 |
137 | // Max - Find highest value
138 | func Max(x, y float64) float64 {
139 | return math.Max(x, y)
140 | }
141 |
142 | // Min - Find lowest value
143 | func Min(x, y float64) float64 {
144 | return math.Min(x, y)
145 | }
146 |
147 | // Pi - Get value of pi
148 | func Pi() float64 {
149 | return math.Pi
150 | }
151 |
152 | // Pow - Exponential expression
153 | func Pow(x, y float64) float64 {
154 | return math.Pow(x, y)
155 | }
156 |
157 | // Rand - Generate a random integer
158 | func Rand(num ...int) int {
159 | rand.Seed(time.Now().Unix())
160 | if l := len(num); l == 1 && num[0] >= 1 {
161 | return rand.Intn(num[0] + 1)
162 | } else if l >= 2 && num[0] < num[1] {
163 | return num[0] + rand.Intn(num[1]-num[0]+1)
164 | }
165 | return rand.Int()
166 | }
167 |
168 | // Round - Rounds a float
169 | func Round(x float64) float64 {
170 | return math.Round(x)
171 | }
172 |
173 | // Sin - Sine
174 | func Sin(x float64) float64 {
175 | return math.Sin(x)
176 | }
177 |
178 | // Sinh - Hyperbolic sine
179 | func Sinh(x float64) float64 {
180 | return math.Sinh(x)
181 | }
182 |
183 | // Sqrt - Square root
184 | func Sqrt(x float64) float64 {
185 | return math.Sqrt(x)
186 | }
187 |
188 | // Tan - Tangent
189 | func Tan(x float64) float64 {
190 | return math.Tan(x)
191 | }
192 |
193 | // Tanh - Hyperbolic tangent
194 | func Tanh(x float64) float64 {
195 | return math.Tanh(x)
196 | }
197 |
--------------------------------------------------------------------------------
/php/strings.go:
--------------------------------------------------------------------------------
1 | package php
2 |
3 | import (
4 | "fmt"
5 | "html"
6 | "regexp"
7 | "strconv"
8 | "strings"
9 | "unicode/utf8"
10 | )
11 |
12 | // Constants for StrPad
13 | const (
14 | StrPadRight = "STR_PAD_RIGHT"
15 | StrPadLeft = "STR_PAD_LEFT"
16 | )
17 |
18 | // Bin2hex - Convert binary data into hexadecimal representation
19 | func Bin2hex(b string) string {
20 | base, err := strconv.ParseInt(b, 2, 64)
21 | if err != nil {
22 | return ""
23 | }
24 | return strconv.FormatInt(base, 16)
25 | }
26 |
27 | // Bindec - Binary to decimal
28 | func Bindec(b string) int64 {
29 | i, _ := strconv.ParseInt(b, 2, 64)
30 | return i
31 | }
32 |
33 | // Hex2bin - Decodes a hexadecimally encoded binary string
34 | func Hex2bin(x string) string {
35 | base, err := strconv.ParseInt(x, 16, 64)
36 | if err != nil {
37 | return ""
38 | }
39 | return strconv.FormatInt(base, 2)
40 | }
41 |
42 | // Chr - Return a specific character
43 | func Chr(ascii int) string {
44 | for ascii < 0 {
45 | ascii += 256
46 | }
47 | return fmt.Sprintf("%c", ascii%256)
48 | }
49 |
50 | // Ord - Return ASCII value of character
51 | func Ord(s byte) byte {
52 | return s
53 | }
54 |
55 | // Explode - Split a string by string
56 | func Explode(s, sep string) []string {
57 | return strings.Split(s, sep)
58 | }
59 |
60 | // GetHtmlTranslationTable - Returns the translation table used by htmlspecialchars() and htmlentities()
61 | func GetHtmlTranslationTable() map[string]string {
62 | return map[string]string{
63 | `"`: """,
64 | `&`: "&",
65 | `<`: "<",
66 | `>`: ">",
67 | }
68 | }
69 |
70 | // Htmlspecialchars - Convert special characters to HTML entities
71 | func Htmlspecialchars(s string) string {
72 | return html.EscapeString(s)
73 | }
74 |
75 | // HtmlspecialcharsDecode - Convert special HTML entities back to characters
76 | func HtmlspecialcharsDecode(s string) string {
77 | return html.UnescapeString(s)
78 | }
79 |
80 | // Implode - Join array elements with a string
81 | func Implode(a []string, sep string) string {
82 | return strings.Join(a, sep)
83 | }
84 |
85 | // Join - Alias of implode()
86 | func Join(a []string, sep string) string {
87 | return Implode(a, sep)
88 | }
89 |
90 | //StripTags - Strip HTML and PHP tags from a string
91 | func StripTags(s string) string {
92 | reg, _ := regexp.Compile(`<[\S\s]+?>`)
93 | s = reg.ReplaceAllStringFunc(s, strings.ToLower)
94 | //remove style
95 | reg, _ = regexp.Compile(`