Skip to content

Commit

Permalink
add directory functions
Browse files Browse the repository at this point in the history
  • Loading branch information
hyperjiang committed Nov 19, 2019
1 parent 9cbdd72 commit 03d8428
Show file tree
Hide file tree
Showing 16 changed files with 114 additions and 39 deletions.
8 changes: 8 additions & 0 deletions README.md
Expand Up @@ -170,6 +170,14 @@ This package implements some PHP functions by Golang. Please note that it's impo
| [file_get_contents](https://www.php.net/manual/en/function.file-get-contents.php) | [FileGetContents](https://godoc.org/github.com/hyperjiang/php#FileGetContents) |
| [file_put_contents](https://www.php.net/manual/en/function.file-put-contents.php) | [FilePutContents](https://godoc.org/github.com/hyperjiang/php#FilePutContents) |

### Directory Functions

| PHP function | Golang function |
| ---------------------------------------------------- | ---------------------------------------------------------- |
| [getcwd](https://www.php.net/manual/en/function.getcwd.php) | [Getcwd](https://godoc.org/github.com/hyperjiang/php#Getcwd) |
| [chdir](https://www.php.net/manual/en/function.chdir.php) | [Chdir](https://godoc.org/github.com/hyperjiang/php#Chdir) |
| [scandir](https://www.php.net/manual/en/function.scandir.php) | [Scandir](https://godoc.org/github.com/hyperjiang/php#Scandir) |

### Image Functions

| PHP function | Golang function |
Expand Down
2 changes: 1 addition & 1 deletion array.go
Expand Up @@ -369,7 +369,7 @@ func ArrayPop(s *[]interface{}) interface{} {
}

// ArrayPush pushes one or more elements onto the end of array,
// returns the new number of elements in the array.
// returns the new number of elements in the array
func ArrayPush(s *[]interface{}, elements ...interface{}) int {
if s == nil {
return 0
Expand Down
27 changes: 14 additions & 13 deletions ctype.go
Expand Up @@ -2,73 +2,74 @@ package php

import "regexp"

// CtypeAlnum returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.
// CtypeAlnum returns TRUE if every character in text is either a letter or a digit, FALSE otherwise
func CtypeAlnum(text string) bool {
reg := regexp.MustCompile("^[[:alnum:]]+$") // same pattern ^[a-zA-Z0-9]+$
return reg.MatchString(text)
}

// CtypeAlpha returns TRUE if every character in text is a letter, FALSE otherwise.
// CtypeAlpha returns TRUE if every character in text is a letter, FALSE otherwise
func CtypeAlpha(text string) bool {
reg := regexp.MustCompile("^[[:alpha:]]+$") // same pattern ^[A-Za-z]+$
return reg.MatchString(text)
}

// CtypeCntrl returns TRUE if every character in text is a control character from the current locale, FALSE otherwise.
// CtypeCntrl returns TRUE if every character in text is a control character from the current locale, FALSE otherwise
func CtypeCntrl(text string) bool {
reg := regexp.MustCompile("^[[:cntrl:]]+$") // same pattern ^[\x00-\x1f\x7f]+$
return reg.MatchString(text)
}

// CtypeDigit returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.
// CtypeDigit returns TRUE if every character in the string text is a decimal digit, FALSE otherwise
func CtypeDigit(text string) bool {
reg := regexp.MustCompile("^[[:digit:]]+$") // same pattern ^[0-9]+$
return reg.MatchString(text)
}

// CtypeGraph returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.
// CtypeGraph returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise
func CtypeGraph(text string) bool {
reg := regexp.MustCompile("^[[:graph:]]+$") // same pattern ^[!-~]+$
return reg.MatchString(text)
}

// CtypeLower returns TRUE if every character in text is a lowercase letter.
// CtypeLower returns TRUE if every character in text is a lowercase letter
func CtypeLower(text string) bool {
reg := regexp.MustCompile("^[[:lower:]]+$") // same pattern ^[a-z]+$
return reg.MatchString(text)
}

// CtypePrint returns TRUE if every character in text will actually create output (including blanks).
// CtypePrint returns TRUE if every character in text will actually create output (including blanks),
// returns FALSE if text contains control characters or characters that do not have any output
// or control function at all.
// or control function at all
func CtypePrint(text string) bool {
reg := regexp.MustCompile("^[[:print:]]+$") // same pattern ^[ -~]+$
return reg.MatchString(text)
}

// CtypePunct returns TRUE if every character in text is printable,
// but neither letter, digit or blank, FALSE otherwise.
// but neither letter, digit or blank, FALSE otherwise
func CtypePunct(text string) bool {
reg := regexp.MustCompile("^[[:punct:]]+$") // same pattern ^[!-\\/\\:-@\\[-`\\{-~]+$
return reg.MatchString(text)
}

// CtypeSpace returns TRUE if every character in text creates some sort of white space, FALSE otherwise.
// CtypeSpace returns TRUE if every character in text creates some sort of white space, FALSE otherwise
//
// Besides the blank character this also includes tab, vertical tab, line feed, carriage return
// and form feed characters.
// and form feed characters
func CtypeSpace(text string) bool {
reg := regexp.MustCompile("^[[:space:]]+$") // same pattern ^[\\s]+$
return reg.MatchString(text)
}

// CtypeUpper returns TRUE if every character in text is an uppercase letter.
// CtypeUpper returns TRUE if every character in text is an uppercase letter
func CtypeUpper(text string) bool {
reg := regexp.MustCompile("^[[:upper:]]+$") // same pattern ^[A-Z]+$
return reg.MatchString(text)
}

// CtypeXdigit returns TRUE if every character in text is a hexadecimal 'digit',
// that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise.
// that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise
func CtypeXdigit(text string) bool {
reg := regexp.MustCompile("^[[:xdigit:]]+$") // same pattern ^[A-Fa-f0-9]+$
return reg.MatchString(text)
Expand Down
1 change: 0 additions & 1 deletion datetime_test.go
Expand Up @@ -10,7 +10,6 @@ import (
)

var _ = Describe("Date/Time Functions", func() {

It("Strtotime", func() {
ts170101 := int64(1483228800) // the UTC timestamp of 2017-01-01
ts170111 := int64(1484092800) // the UTC timestamp of 2017-01-11
Expand Down
29 changes: 29 additions & 0 deletions directory.go
@@ -0,0 +1,29 @@
package php

import (
"os"
)

// Getcwd gets the current working directory, it will return empty string when error occurs
func Getcwd() string {
dir, _ := os.Getwd()
return dir
}

// Chdir changes current directory to dir
func Chdir(dir string) error {
return os.Chdir(dir)
}

// Scandir lists files and directories inside the specified path
func Scandir(dir string) ([]string, error) {
f, err := os.Open(dir)
if err != nil {
return nil, err
}

names, err := f.Readdirnames(-1)
f.Close()

return names, err
}
29 changes: 29 additions & 0 deletions directory_test.go
@@ -0,0 +1,29 @@
package php_test

import (
"github.com/hyperjiang/php"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)

var _ = Describe("Directory Functions", func() {
It("Chdir and Getcwd", func() {
var dir = php.Getcwd()
Expect(dir).NotTo(BeEmpty())

var err = php.Chdir(dir + "/tmp")
Expect(err).To(HaveOccurred(), "no such file or directory")
})

It("Scandir", func() {
var names, err = php.Scandir(".")
Expect(err).NotTo(HaveOccurred())
Expect(names).NotTo(BeEmpty())

_, err = php.Scandir("./tmp")
Expect(err).To(HaveOccurred(), "no such directory")

_, err = php.Scandir("./README.md")
Expect(err).To(HaveOccurred(), "no such directory")
})
})
4 changes: 2 additions & 2 deletions filesystem.go
Expand Up @@ -47,7 +47,7 @@ func Unlink(filename string) error {
return syscall.Unlink(filename)
}

// Mkdir attempts to create the directory specified by pathname.
// Mkdir attempts to create the directory specified by pathname
func Mkdir(pathname string, mode os.FileMode, recursive bool) error {
if mode == 0 {
mode = 0777
Expand Down Expand Up @@ -128,7 +128,7 @@ func IsLink(filename string) bool {
return fi.Mode()&os.ModeSymlink == os.ModeSymlink
}

// Copy copies the src file to dst. Any existing file will be overwritten and will not copy file attributes.
// Copy copies the src file to dst, any existing file will be overwritten and will not copy file attributes
func Copy(src, dst string) error {
in, err := os.Open(src)
if err != nil {
Expand Down
1 change: 0 additions & 1 deletion filesystem_test.go
Expand Up @@ -9,7 +9,6 @@ import (
)

var _ = Describe("Filesystem Functions", func() {

It("Dirname", func() {
tests := []struct {
input string
Expand Down
5 changes: 5 additions & 0 deletions go.mod
@@ -1,3 +1,8 @@
module github.com/hyperjiang/php

go 1.11

require (
github.com/onsi/ginkgo v1.10.3
github.com/onsi/gomega v1.7.1
)
7 changes: 4 additions & 3 deletions json.go
Expand Up @@ -4,14 +4,15 @@ import (
"encoding/json"
)

// JSONEncode returns a string containing the JSON representation of the supplied value.
// JSONEncode returns a string containing the JSON representation of the supplied value
func JSONEncode(value interface{}) (string, error) {
b, err := json.Marshal(value)
return string(b), err
}

// JSONDecode decodes a JSON string and stores the result in the value pointed to by v.
// Be aware that this is different with php json_decode.
// JSONDecode decodes a JSON string and stores the result in the value pointed to by v
//
// Be aware that this is different with php json_decode
func JSONDecode(jsonStr string, v interface{}) error {
return json.Unmarshal([]byte(jsonStr), v)
}
2 changes: 1 addition & 1 deletion math.go
Expand Up @@ -41,7 +41,7 @@ func Round(val float64, precision int) float64 {
return res
}

// Abs returns the absolute value of number.
// Abs returns the absolute value of number
func Abs(number float64) float64 {
return math.Abs(number)
}
Expand Down
1 change: 0 additions & 1 deletion math_test.go
Expand Up @@ -7,7 +7,6 @@ import (
)

var _ = Describe("Math Functions", func() {

It("Round", func() {
type args struct {
val float64
Expand Down
11 changes: 7 additions & 4 deletions misc.go
Expand Up @@ -12,7 +12,8 @@ func Getenv(varname string) string {
return os.Getenv(varname)
}

// Putenv sets the value of an environment variable.
// Putenv sets the value of an environment variable
//
// The setting should be a key-value pair, like "FOO=BAR"
func Putenv(setting string) error {
s := strings.Split(setting, "=")
Expand All @@ -22,9 +23,11 @@ func Putenv(setting string) error {
return os.Setenv(s[0], s[1])
}

// MemoryGetUsage returns the amount of allocated memory in bytes.
// Set realUsage to TRUE to get total memory allocated from system, including unused pages.
// If realUsage is FALSE then only the used memory is reported.
// MemoryGetUsage returns the amount of allocated memory in bytes
//
// Set realUsage to TRUE to get total memory allocated from system, including unused pages
//
// If realUsage is FALSE then only the used memory is reported
func MemoryGetUsage(realUsage bool) uint64 {
stat := new(runtime.MemStats)
runtime.ReadMemStats(stat)
Expand Down
20 changes: 11 additions & 9 deletions phpstr.go
Expand Up @@ -28,17 +28,17 @@ const (
// RuneMatchFunc is function to check if a rune match some condition
type RuneMatchFunc func(rune) bool

// Substr returns the portion of string specified by the start and length parameters.
// Substr returns the portion of string specified by the start and length parameters
//
// The behaviour of this function is mostly the same as the PHP mb_substr function,
//
// see http://php.net/manual/en/function.mb-substr.php
//
// except that:
//
// 1) If start or length is invalid, empty string will be return;
// 1) If start or length is invalid, empty string will be return
//
// 2) If length is 0, the substring starting from start until the end of the string will be returned.
// 2) If length is 0, the substring starting from start until the end of the string will be returned
func Substr(str string, start, length int) string {

rs := []rune(str)
Expand Down Expand Up @@ -207,7 +207,7 @@ func Ireplace(search, replace interface{}, subject string) string {

// Addslashes quote string with slashes
//
// The characters to be escaped are single quote ('), double quote (") and backslash (\).
// The characters to be escaped are single quote ('), double quote (") and backslash (\)
func Addslashes(str string) string {
return Replace([]string{"\\", "'", "\""}, []string{"\\\\", "\\'", "\\\""}, str)
}
Expand All @@ -232,13 +232,13 @@ func Ord(character string) rune {
}

// Explode returns an slice of strings, each of which is a substring of str
// formed by splitting it on boundaries formed by the string delimiter.
// formed by splitting it on boundaries formed by the string delimiter
func Explode(delimiter, str string) []string {
return strings.Split(str, delimiter)
}

// Implode returns a string containing a string representation of all the slice
// elements in the same order, with the glue string between each element.
// elements in the same order, with the glue string between each element
func Implode(glue string, pieces []string) string {
return strings.Join(pieces, glue)
}
Expand Down Expand Up @@ -362,9 +362,11 @@ func StrWordCount(str string) []string {

// NumberFormat formats a number with grouped thousands
//
// decimals: sets the number of decimal points.
// decPoint: sets the separator for the decimal point.
// thousandsSep: sets the thousands separator.
// decimals: sets the number of decimal points
//
// decPoint: sets the separator for the decimal point
//
// thousandsSep: sets the thousands separator
func NumberFormat(number float64, decimals int, decPoint, thousandsSep string) string {
if decimals < 0 {
decimals = 0
Expand Down
1 change: 0 additions & 1 deletion phpstr_test.go
Expand Up @@ -7,7 +7,6 @@ import (
)

var _ = Describe("String Functions", func() {

It("Substr", func() {
str := "abcdef"
tests := []struct {
Expand Down
5 changes: 3 additions & 2 deletions similar_text.go
Expand Up @@ -3,8 +3,9 @@ package php
// SimilarText calculate the similarity between two strings
// returns the number of matching chars in both strings and the similarity percent
// note that there is a little difference between the original php function that
// a multi-byte character is counted as 1 while it would be 2 in php.
// This function is case sensitive.
// a multi-byte character is counted as 1 while it would be 2 in php
//
// This function is case sensitive
func SimilarText(first, second string) (count int, percent float32) {
txt1 := []rune(first)
len1 := len(txt1)
Expand Down

0 comments on commit 03d8428

Please sign in to comment.